Vuex centrally manages the state of all components of an application and has rules to ensure that state changes in a predictable way.

Install vuex

vue add vuex
Copy the code

Key Concepts:

State Indicates the status and data

Mutations is a function of changing state

Actions Asynchronous operations

Store A container containing the above concepts

State – the state

export default new Vuex.Store({
state: { counter:0 },
})
Copy the code

Status changes. – Mutations

export default new Vuex.Store({
mutations: {
add(state) {
state.counter++
 }
 }
})
Copy the code

Derived state – getters

Export default new vuex. Store({getters: {doubleCounter(state) {return state.counter * 2; }}})Copy the code

Action – the actions

export default new Vuex.Store({ actions: { add({ commit }) { setTimeout(() => { commit('add') }, 1000); }}})Copy the code

Principle analysis:

To achieve the Store class

Maintain a reactive state

Implement the commit ()

Realize the dispatch ()

       getters

Mount $store

Key points:

Initialization: Store declaration, install implementation,

let Vue; class Store { constructor(options = {}) { this._vm = new Vue({ data: { $$state:options.state } }); } get state() { return this._vm._data.$$state } set state(v) { console.error('please use replaceState to reset state'); } } function install(_Vue) { Vue = _Vue; Vue.mixin({ beforeCreate() { if (this.$options.store) { Vue.prototype.$store = this.$options.store; }}}); }export default { Store, install };Copy the code

Implement COMMIT: obtain and perform mutation based on the type passed in by the user

Class Store {constructor (options = {}) {/ / save the mutations of user configuration options for this. _mutations = options. The mutations | | {}} to commit (type, = this._mutations[type] if (! entry) { console.error(`unknown mutation type: ${type}`); // pass state to mutation entry(this.state, payload); }}Copy the code

Implement actions: Retrieve and execute actions based on the type passed in by the user

Class Store {constructor (options = {}) {/ / save the user write actions options this. _actions = options. Actions | | {} / / Bind the commit context or the action may fail to call commit!! // Also bind the action, Const store = this const {commit, action} = store this.mit = function boundCommit(type, payload) { commit.call(store, type, payload) } this.action = function boundAction(type, payload) { return action.call(store, type, payload) } } dispatch(type, Payload) {// Get action const entry = this._actions[type] Web full stack architect if (! entry) { console.error(`unknown action type: ${type}`); // Asynchronous result processing often requires a return Promise return entry(this, payload); }}Copy the code