preface
Recently, in order to go out for an interview, I summarized what I learned. Suddenly, I found that some of my things only stayed in the stage of knowing how to use them, and I did not know how to implement them. Therefore, I have this article.
The core concept
Vuex stores states that need to be shared in a centralized manner. It is a state management library specifically designed for VUE. State: Data source view that drives the application: State is declaratively mapped to view Actions in response to state changes caused by user input on the view
The state API is used to store data. It is used to store data. It is used to perform a simple operation on the data stored in the state API. The data is mainly processed asynchronously, but mutation is still used to avoid error modules in VueTools: multiple store classes can be generated
So let’s do a simple implementation of the Store class
To simulate the Store class
let _Vue = null
class Store{
cinstructor (options) {
const {
state = {},
getters = {}
mutations = {}
actions = {}
} = optinos
this.state = _Vue.observable(state)
this.getters = Object.create(null)
Object.keys(getters).forEach(key => {
Object.defineProperty(this.getters, key, {
get: ()=> getters[key](state)
})
})
this._mutations = mutations
this._actions = actions
commit ( type,payload ) {
this._mutations[type](this.state, payload)
}
dispatch (type, payload) {
this._actions[type]( this , payload)
}
}
}
Copy the code
1. If we want to use it, we will inject the store object passed in when creating the Vue instance into the $store on the Vue prototype
The vuEX repository can be accessed from this.$store in all components, so that state can be shared among all components.
3. In install, we can not get the Vue instance, so we can use beforeCreate to get the Vue instance, and get the store object
The next step is to simulate the mount install method
Simulate the install method
function install (Vue) { _Vue = Vue _Vue.mixin({ beforeCreate () { if (this.$options.store) { // Prototype.$store = this.$options.store}})}Copy the code
And then finally we can export it
export default {
Store,
install
}
Copy the code