Member-only story

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

Liu Ting Chun
3 min readDec 11, 2019

If you have played with Angular before, you must be familiar with services in the Angular ecosystem. They are isolated singleton objects that you can use to organize your shared functions. For example, you may have an AuthenticationService which handle all the login, logout, token refresh, etc.

This concept doesn’t exist in Vue. Vue encourages using Mixin and Store instead of isolated stateful object to organize shared logic. Yet, if you love Angular (like me :D) and you want to stick with the Angular methodology even in Vue (and you don’t care about best practices), here is what you can do to create an Angular-like service in Vue.

Creating importable singleton objects in JS

It is actually quite simple to create a singleton object. Simply define your class and export an instance instead of the class definition, then it will be singleton.

In my.service.js:

class MyService {
myVar = 1;

constructor() {

}

myMethod() {
return this.myVar;
}
}
export default new MyService();

In your component:

<template>
<div>{{test}}</div>
</template>
<script>
import myService from…

--

--

Liu Ting Chun
Liu Ting Chun

Written by Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

Responses (2)