Skip to content
Advertisement

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.

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement