Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
vue使用vuex插件
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
Js
//根状态对象。
//每个vuex实例只是一个单一的状态树。
const state = {
locale : 'zh'
};
//突变操作,实际上变异状态。
//每个突变处理程序将整个状态树作为
//第一个参数,其次是额外的有效载荷参数。
//突变必须是同步的,可以通过插件记录
//为了调试目的。
const mutations = {
CHANGE_LOCALE(state,locale){
state.locale = locale;
}
};
//行动是导致副作用和可能涉及的功能
//异步操作。
const actions = {
CHANGE_LOCALE({commit},locale){
commit('CHANGE_LOCALE',locale);
}
};
// getter函数
const getters = {
getLocale: state => state.locale
}
// vuex实例相结合的状态,突变,getter函数、行动
export default new Vuex.Store({
state,
mutations,
getters,
actions
});
组件文件中通过locale属性相关联