Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: define a service

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.

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?

I considered vue-resource, but it's only for http functionalities as far as I understand. As I use jQuery too, this is obsolete.

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.

like image 903
Herr Derb Avatar asked Jul 21 '16 08:07

Herr Derb


People also ask

Are there services in Vue?

There are no such services that could be injected in components. Show activity on this post. You can make your own service where you can place all your HTTP server calls and then import that to the components where you want to use them.

Does Vue have services like angular?

js — Using a stateful Angular-like service to organize your code.

How do I get Vue CLI service?

You can access the binary directly as vue-cli-service in npm scripts, or as ./node_modules/. bin/vue-cli-service from the terminal. You can run scripts with additional features using the GUI with the vue ui command.


1 Answers

From the Vue.js documentation.

Vue.js itself is not a full-blown framework - it is focused on the view layer only.

As a library focusing on the V out of MVC it does not provide things like services.

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.

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.

import RestResource from './services/RestResource';  const restResourceService = new RestResource();  restResourceService.sendRequest(); 
like image 148
Marc Avatar answered Sep 22 '22 07:09

Marc