Vuex is a tool we often use in the development of VUE projects, so today we will implement a simple version of Vuex
What is a vuex?
Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.
Basic use of vuex
// store.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
text: "Hello Vuex"
},
getters: {},
mutations: {},
actions: {},
modules: {})}Copy the code
Implementation of simple vuex
let Vue
// Create a store class
class Store {
constructor(options) {
// 1. Save the options passed in
this._mutations = options.mutaitions
this._actions = options.actions
// 2. Respond to the state option passed in
this._vm = new Vue({
data() {
return {
$$state: options.state
}
}
})
// Bind the context to make sure it is a Store instance
this.commit = this.commit.bind(this)
this.dispatch = this.dispatch.bind(this)}// When the user reads state in store, it actually goes here
get state () {
return this._vm.$$state
}
// An error is reported when a user attempts to modify data in state. Only commit is allowed
set state (v) {
console.error('please use replaceState to reset state');
}
// Implement commit
commit(type, payload) {
const entry = this._mutations[type] // Match the corresponding mutation based on the field passed in
if(! entry) {console.error('unknown mutation')
}
entry(this.state, payload) // perform the mutation and pass in the state and the payload for the commit
}
// Implement the dispatch method
dispatch (type, payload) {
const entry = this._actions[type] // Match the corresponding action based on the field passed in
if(! entry) {console.error('unknown action')
}
entry(this, payload) // Distribute the dispatch and pass in the Store instance}}Implement the install method
function install(_Vue) {
Vue = _Vue
// Hang the Store instance to Vue when the install method is executed in vue.use ()
Vue.mixin({
beforeCreate () {
// This refers to the vue instance
if (this.$options.store) {
Vue.prototype.$store = this.$options.store
}
}
})
}
// Expose the Stroe class and install method externally
export default { Stroe, install }
Copy the code