state :存储状态。也就是变量;
getters :派生状态。也就是 set 、 get 中的 get ,有两个可选参数: state 、 getters 分别可以获取 state 中的变量和其他的 getters 。外部调用方式: store.getters.personInfo() 。就和 vue 的 computed 差不多;
mutations :提交状态修改。也就是 set 、 get 中的 set ,这是 vuex 中唯一修改 state 的方式,但不支持异步操作。第一个参数默认是 state 。外部调用方式: store.commit(‘SET_AGE’, 18) 。和 vue 中的 methods 类似。
actions :和 mutations 类似。不过 actions 支持异步操作。第一个参数默认是和 store 具有相同参数属性的对象。外部调用方式: store.dispatch(‘nameAsyn’) 。
modules : store 的子模块,内容就相当于是 store 的一个实例。调用方式和前面介绍的相似,只是要加上当前子模块名,如: store.a.getters.xxx()
1.3 vue-cli中使用vuex的方式
目录结构
├── index.html
├── main.js
├── components
└── store
├── index.js # 我们组装模块并导出 store 的地方
├── state.js # 跟级别的 state
├── getters.js # 跟级别的 getter
├── mutation-types.js # 根级别的mutations名称(官方推荐mutions方法名使用大写)
├── mutations.js # 根级别的 mutation
├── actions.js # 根级别的 action
└── modules
├── m1.js # 模块1
└── m2.js # 模块2
state示例
const state = {
name: 'weish',
age: 22
};export default state;
getter示例
getters.js 示例(我们一般使用 getters 来获取 state 的状态,而不是直接使用 state )
export const name = (state) => {
return state.name;
}export const age = (state) => {
return state.age
}
export const other = (state) => {
return `My name is ${state.name}, I am ${state.age}.`;
}
mutation-type示例
将所有 mutations 的函数名放在这个文件里
export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';
mutations示例
import * as types from './mutation-type.js';export default {
[types.SET_NAME](state, name) {
state.name = name;
},
[types.SET_AGE](state, age) {
state.age = age;
}
};
actions示例
异步操作、多个 commit 时
import * as types from './mutation-type.js';










