How to make a simple vuex use:
Install:
npm i vuex --save-dev
Create a new folder store,
Index.js build a file in the store folder in the file:
Import view from 'View'
import vuex from 'vuex'
Vue.use(vuex)
var state = {// state attributes that need to be stored in the data vuex
name: "Computer"
age:2,
data: 'blabla'
}
var actions = {// asynchronous method, such as defined here is a method called changeName
changeName(context,name){
context.commit('changeName',name)
}
}
var mutations = {// synchronization method, the methods described herein is preferably the same as named above, there are such changeName
changeName(state,newName){
state.name = newName // newName state is changed in name
}
}
was large = new vuex.Store ({
state,
actions,
mutations
})
export default store
=================================================================
In main.js file, the introduction of store:
import store from './store' // vuex state manager
new view ({
el:"#app",
router,
store
})
// call the data state in the assembly: for example, name the way
{{$store.state.name}}
// method to trigger change in the components, the way changeName method vuex in before calling this method:
<Button @ click = "change"> name change </ button>
{
methods:{
change(){
// This step is vuex in changeName (state, newName) {state.name = newName} corresponds to this, in the name vuex was modified into 'new computer'
this. $ store.dispatch ( "changeName", 'new computer')
}
}
}
to sum up:
state: the data stored in the vuex
actions: asynchronous method defined in
mutations: synchronization method defined in
this $ store.dispatch ( "changeName", 'new computer'): the calling method vuex, parameter passing mode
$ Store.state.name: vuex in data usage, such as using the name of fashion