If you want to use VUEX to realize a simple singleton, the advantage is better inter-component linkage experience, but the disadvantage is that there are many pits and the coupling degree is higher. If you want to use vuEX in actual projects, you’d better optimize and improve the overall mechanism

The singleton pattern is implemented as follows:

class Instance{ constructor(){ this.relyOn = {} } static getInstance(){ if(! this.instance){ this.instance = new Instance() } return this.instance } add(obj){ Object.assign(this.relyOn,obj) return this.relyOn } commit(name){ return this.relyOn[name] } } export default Instance.getInstance()Copy the code

Vuex internal methods are as follows:

import { createStore } from 'vuex' import instance from './instance.js' export default createStore({ mutations: { signIn($scope,params){ if(typeof params === "object") return instance.add(params); if(typeof params === "string") return instance.commit(params)(); Throw new Error(" parameter invalid "); }}})Copy the code

When called in vue instance, use signIn to register and call the registered method. If the registered method is associated with this of vue instance, we should consider whether the instance is the instance before destruction or the instance generated after destruction. If the instance generated again, the function has been invalid.

There are many aspects to improve: 1, function container recycling and overwriting mechanism; 2. If you want to use such a mechanism in your project, you must find a way to reduce the coupling degree; 3. Vuex can not only cooperate with singletons but also with other design modes. It is not limited to its form.