打算开发中大型应用,集中式数据管理, 一处修改,多处使用,多个组件依赖于同一状态,来自不同组件的行为需要变更同一状态,生态环境给我们提供了官方插件vuex
vuex相关成员
import Vuex from 'vuex'
, Vuex是个对象,相关成员如下
成员 | 用途 |
---|---|
Store | 类,构造状态管理的实例 |
mapActions | 函数,通讯工具 |
mapMutations | 函数,通讯工具 |
mapGetters | 函数,通讯工具 |
mapState | 函数,通讯工具 |
状态管理实例相关成员
成员 | 用途 |
---|---|
dispatch | 实例方法,通讯工具 |
commit | 实例方法,通讯工具 |
state | 属性,获取公共数据 |
角色分工
components-> | actions-> | mutations-> | state | <-getters-> | ->components |
---|---|---|---|---|---|
发送请求 | 处理业务,异步 | 修改状态 | 状态 | 读取状态 | 渲染状态 |
学生 | 代课老师 | 校长 | 财务 | 班主任 | 学生 |
dispatch | commit | state.key=value | {key:value} | state.key | {{key}} |
mapActions-> | <-mapGetters | ||||
mapMutations-> | -------------------> | <------------ | <-mapState |
配置
// /src/main.js
//引入store实例
import store from ‘./plugins/vuex.js’
new Vue({
render: h => h(App),
store//控制vue实例,为vue实例提供一个状态管理实例,管理整个vue公共状态
}).$mount(’#app’)
// src/plugins/vuex.js
//配置 store
import Vue from ‘vue’;
import Vuex from ‘vuex’;//引入vuex包
Vue.use(Vuex);//安装插件到vue
import state from ‘…/store/state.js’
import actions from ‘…/store/actions.js’
import mutations from ‘…/store/mutations.js’
import getters from ‘…/store/getters.js’
let store = new Vuex.Store({//配置接受state等选项,值为对象
state,mutations,
getters,actions
});
export default store;//导出store实例给main.js
// src/store/state.js
let state={
count:0
}
export default state;
// src/store/actions
let actions = {
jia:({commit,state},payload)=>{
//state 公共状态 payload 负载
commit(‘increment’,payload)
}
};
export default actions;
// src/store/mutations.js
let mutations={
increment:(state,payload)=>{
//state 仓库|公共数据 payload携带的负载
state.count+=payload;//mutations 不做业务,只负责突变state
}
};
export default mutations;
// src/store/getters.js
let getters = {
count:(state)=>{
//返回处理后的state ~~ computed
return state.count % 2 === 0 ? state.count + ‘偶数’: state.count + ‘奇数’
}
};
export default getters;