转载:https://segmentfault.com/a/1190000015782272
Vue的vuex和React的Redux 都统称为同一状态管理,简单的理解就是在state中定义了一个数据之后,在项目中的任何一个组件里进行获取、进行修改,并且修改的内容可以得到全局的响应变更。
npm install vuex --save
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={ //要设置的全局访问的state对象
showFooter: true,
changableNum:0
//要设置的初始属性值
};
//实时监听state值的变化(最新状态)
const getters = {
isShow(state) { //承载变化的showFooter的值
return state.showFooter
},
getChangedNum(){ //承载变化的changebleNum的值
return state.changableNum
}
};
//mutattions也是一个对象,这个对象里面可以放改变state的初始值的方法,
const mutations = {
show(state) { //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
state.showFooter = true;
},
hide(state) { //同上
state.showFooter = false;
},
newNum(state,sum){ //同上,这里面的参数除了state之外还传了需要增加的值sum
state.changableNum+=sum;
}
};
//这个actions也是个对象变量,最大的作用就是里面的Action方法 可以包含任意异步操作,这里面的方法是用来异步触发mutations里面的方法,actions里面自定义的函数接收一个context参数和要变化的形参,context与store实例具有相同的方法和属性
const actions = {
hideFooter(context) { //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性
context.commit('hide');
},
showFooter(context) { //同上注释
context.commit('show');
},
getNewNum(context,num){ //同上注释,num为要变化的形参
context.commit('newNum',num)
}
};
const store = new Vuex.Store({
state,
getters,
mutations,
actions
});
export default store;
而在外部组件里进行全局执行actions里面方法的时候,你只需要用执行
this.$store.dispatch('hideFooter')
或this.$store.dispatch('showFooter')
以及this.$store.dispatch('getNewNum',6)