Javascript Vue.js:定义一个服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38498427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue.js: define a service
提问by Herr Derb
I'm looking at Vue.js as an alternative to Angular and I really like it so far. To get a feeling for it, I'm refactoring an existing Angular project to a Vue project. I'm just at the point where I need to communicate with my REST API.
我正在将 Vue.js 视为 Angular 的替代品,到目前为止我真的很喜欢它。为了感受一下,我正在将一个现有的 Angular 项目重构为一个 Vue 项目。我正处于需要与我的 REST API 通信的地步。
In Angular I used to define a service for that, that was injected into every controller that needed it. Vue doesn't seem to know the "service" construct as I understand. How can this be achieved in Vue?
在 Angular 中,我曾经为此定义了一个服务,该服务被注入到每个需要它的控制器中。据我所知,Vue 似乎不知道“服务”构造。这在 Vue 中如何实现?
I considered vue-resource
, but it's only for http functionalities as far as I understand. As I use jQuery too, this is obsolete.
我考虑过vue-resource
,但据我所知,它仅适用于 http 功能。因为我也使用 jQuery,这已经过时了。
Example:
例子:
I have vueComponent1
and vueComponent2
. Both need access to the same REST resource. To handle this I want a central service, which both of the components can use for requests to the REST resource. Angular has the 'service' component, which exactly does that. Vue hasn't.
我有vueComponent1
和vueComponent2
。两者都需要访问相同的 REST 资源。为了处理这个问题,我需要一个中央服务,两个组件都可以使用它来请求对 REST 资源的请求。Angular 有“服务”组件,它正是这样做的。Vue 没有。
回答by Marc
From the Vue.js documentation.
来自 Vue.js 文档。
Vue.js itself is not a full-blown framework - it is focused on the view layer only.
Vue.js 本身并不是一个成熟的框架——它只关注视图层。
As a library focusing on the V out of MVC it does not provide things like services.
作为一个专注于 MVC 中的 V 的库,它不提供服务之类的东西。
Are you using some kind of module loader like Browserify or Webpack?
Then you can leverage the module system of ES6 to create a service all by yourself.
All you have to do is to create a plain JavaScript class which is being exported by this new module.
你在使用像 Browserify 或 Webpack 这样的模块加载器吗?
然后你就可以利用 ES6 的模块系统自己创建一个服务了。
您所要做的就是创建一个由这个新模块导出的普通 JavaScript 类。
An example could look like this:
一个示例可能如下所示:
export default class RestResource {
sendRequest() {
// Use vue-resource or any other http library to send your request
}
}
Inside your vue component 1 and 2 you can use this service by importing the class.
在 vue 组件 1 和 2 中,您可以通过导入类来使用此服务。
import RestResource from './services/RestResource';
const restResourceService = new RestResource();
restResourceService.sendRequest();
回答by Erick Petrucelli
From the Vue.js documentation on Building Large-Scale Apps.
来自关于构建大型应用程序的 Vue.js 文档。
The community has contributed the vue-resourceplugin, which provides an easy way to work with RESTful APIs. You can also use any Ajax library you like, e.g. $.ajax or SuperAgent.
社区贡献了vue-resource插件,它提供了一种使用 RESTful API 的简单方法。您还可以使用任何您喜欢的 Ajax 库,例如 $.ajax 或SuperAgent。
Vue doesn't require you to follow a specific architecture, since it only refers to the View layer in an MVC or MVVM architecture. As @Marcalready said in his answer, a good practice is to use a module loader like Browserify or Webpack so you can create your "services" in separate files, importing they where you need. It's very easy to structure your app with a module loader using vue-cli.
Vue 不要求您遵循特定的架构,因为它仅指 MVC 或 MVVM 架构中的视图层。正如@Marc在他的回答中已经说过的那样,一个好的做法是使用像 Browserify 或 Webpack 这样的模块加载器,这样你就可以在单独的文件中创建你的“服务”,在你需要的地方导入它们。使用vue-cli使用模块加载器构建您的应用程序非常容易。
Indeed, I personaly really like the Fluxarchitecture for component based apps, then I recommend you to take a look at Vuex, a Flux-inspired application architecture that is designed specifically for managing state inside Vue.js apps.
事实上,我个人非常喜欢基于组件的应用程序的Flux架构,那么我建议您看看Vuex,这是一个受 Flux 启发的应用程序架构,专为管理 Vue.js 应用程序内部的状态而设计。
This way, you can create Actions that use vue-resourceto request your API, then you can dispatch Mutations when the data arrives, with all components that need that data already bound to the global State, reacting automatically. In other words, your components itself don't need to call the services, they just react to State changes dispatched by Mutations.
这样,您可以创建使用vue-resource请求 API 的操作,然后您可以在数据到达时调度 Mutation,所有需要该数据的组件都已绑定到全局状态,并自动做出反应。换句话说,您的组件本身不需要调用服务,它们只对 Mutation 调度的状态更改做出反应。
回答by Max Oriola
You can export the instance of a class for your service:
您可以为您的服务导出类的实例:
export default new class {
...
}
In your component, or any other place, you can import the instance and you will always get the same one. This way it behaves similar to an injected Angular service, but without using this
.
在您的组件或任何其他地方,您可以导入实例,并且您将始终获得相同的实例。这样,它的行为类似于注入的 Angular 服务,但不使用this
.
import myService from '../services/myservice';
Vue.component('my-component', {
...
created: function() {
myService.oneFunction();
}
...
})
回答by Alexander
You have some very good answers to it in this question What's the equivalent of Angular Service in VueJS?
在这个问题中,您有一些很好的答案:VueJS 中的 Angular 服务相当于什么?
As @Otabek Kholikov says there - you have 4 options:
正如@Otabek Kholikov 所说 - 您有 4 个选择:
- Stateless service: then you should use mixins
- Statefull service: use Vuex
- Export service and import from a vue code
- any javascript global object
- 无状态服务:那么你应该使用 mixins
- 有状态服务:使用 Vuex
- 从 vue 代码导出服务和导入
- 任何 javascript 全局对象
In my projects I prefer (4). It gives me the maximum flexibility and has only the implementations I need (I don't bring for example Vuex and shouldn't be strict to its rules and there is no "magic" - all code is mine). You have an example of implementation in the QuestionI mentioned above.
在我的项目中,我更喜欢 (4)。它给了我最大的灵活性,并且只有我需要的实现(我没有带来例如 Vuex,也不应该严格遵守它的规则,也没有“魔法”——所有代码都是我的)。您在我上面提到的问题中有一个实施示例。
回答by Michael Tranchida
If you're not using a module loader, you can define a custom plugin. Some example code:
如果您不使用模块加载器,则可以定义自定义插件。一些示例代码:
var myPlugin = {
install: function (Vue, options) {
//private
var myPrivateProperty = 'Private property';
//instance properties and methods
Vue.prototype.$myPublicProperty = 'Public Property';
Vue.prototype.$myAddedMethod = function () {
return myPrivateProperty;
};
Vue.prototype._getData = function (url) {
return url;
};
//static properties and methods
Vue.myStaticProperty = 'My static prop';
Vue.myStaticMethod = function () {
console.log('in');
}
}
};
Vue.use(myPlugin);
new Vue({
el: '#app',
created: function () {
//using instance
console.log(this.$myAddedMethod());
console.log('my get data: ' + this._getData('some url'));
console.log(this.$myPublicProperty);
//using static
console.log(Vue.myStaticProperty);
Vue.myStaticMethod();
}
});
You can also plug in other libraries, this postshows how to plug in axios.js
也可以插入其他库,这篇文章展示了如何插入axios.js
回答by Sourabh Ranka
You can configure vue resource globally as
您可以将 vue 资源全局配置为
Vue.http.options.root = "your base url"
and now on every http call you can simply call by the name of resource -
现在在每个 http 调用中,您可以简单地按资源名称调用 -
this.$http.get('');
this.$http.get('users')