Vuex is used to manage all component states of the Vue.
First download Vuex, "Vuex": "^3.0.1", the use of "vuex-persistedstate" to cache data. Download "Vuex-persistedstate"
Introduced in the file: (Create a new store folder, the Index.js file under the folder to write as follows)
Import Vue from ' Vue '
import Vuex from ' Vuex '
import createpersistedstate ' vuex-persistedstate
' Vue.use (Vuex)
To define a simple module:
Const MODULE = {State
: {
User: {
name: ' Rookie '
}
},
getters: {},
mutations:
{ SetUser (State, payload) {
if (payload.hasownproperty (' name ')) {
state.user.name = Payload.name
}
}
,
plugins: [Createpersistedstate ()]
}
Above is a simple Vuex, the corresponding store application in Vuex, which contains the shared state of the component in the store and the method of changing the state (referred to as method) mutations. Note that the state is equivalent to an external read-only status and cannot be changed by Store.state.user.name, using the Store.commit method to change the states by triggering the mutations.
Gets the value of the record in the page name is rookie:
Mounted () {
Console.log (this. $store. state.user.name);
}
Store.state to get the value in the store, the value printed on my page is rookie, and we want to modify the value of name, we need to use the Store.commit method to trigger the mutations:
this. $store. Commit (' SetUser ', {name: ' Kuke_kuke '})
SETUSER is found in mutations, and the second parameter payload to the Passed-in object {name: ' Kuke_kuke '}, calling method Hadownproperty to determine whether the incoming object has a name attribute, thereby modifying the value in state. The User.Name value is printed again on the page as ' Kuke _ Kuke '.
Last Export module:
Const STORE = new Vuex.store (module)
Export default Store
Don't forget to get the module in the Main.js and use:
Import store from './store '
new Vue ({
store
})
Author: rookie.he (Kuke_kuke)
Blog Link: http://blog.csdn.net/qq_33599109
Welcome to support, thank you.