Vuex状态管理:
view -> (dispatch) Action -> (commit) Mutations -> (Mutate) State -> (渲染)View
注意:Action非必须,有异步操作才可能用到Action,否则可以不使用
npm install vuex --save
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
count:0//存放的数据
}
})
其他文件中读取:
this.$store.state.count;
mutations:{
increment(state){
state.count++;
}
}
其他文件中调用这个修改方法:
this.$store.commit("increment")
例:
//store
mutations:{
increment(state){
state.count++;
}
},
actions:{
increment(context){
context.commit("increment");//通过commit调用Mutations(Vuex状态管理)
}
}
//这时外部就调用action
//外部:
this.$store.dispatch("increment");
Action提交的是mutation,而不是直接变更状态。
Action可以包含任意异步操作。(mutation不操作异步)
//store操作
getters:{
getState(state){
return state.count>0 ? state.count : 0
}
}
//外部读取
this.$store.getters.getState()
const moduleA = {
state:{...},
mutations:{...},
actions:{...},
getters:{...},
}
const moduleB = {
state:{...},
mutations:{...},
actions:{...},
}
const store = new Vuex Store({
modules:{
a:moduleA,
b:moduleB
}
})
store.state.a//→moduleA的状态
store.state.b//→moduleB的状态
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vue.Store({
state:{...},
mutations:{...},
actions:{...},
})
然后在main.js中import