vue的状态管理模式vuex

2020-06-16 05:50:15易采站长站整理

modules:store的子模块,内容就相当于是store的一个实例。调用方式和前面介绍的相似,只是要加上当前子模块名,如:store.a.getters.xxx()。

vue-cli中使用vuex的方式

一般来讲,我们都会采用vue-cli来进行实际的开发,在vue-cli中,开发和调用方式稍微不同。


├── 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.js示例:


const state = {
name: 'weish',
age: 22
};

export default state;

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.js示例(我们会将所有mutations的函数名放在这个文件里):


export const SET_NAME = 'SET_NAME';
export const SET_AGE = 'SET_AGE';

mutations.js示例:


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.js示例(异步操作、多个commit时):


import * as types from './mutation-type.js';

export default {
nameAsyn({commit}, {age, name}) {
commit(types.SET_NAME, name);
commit(types.SET_AGE, age);
}
};

modules–m1.js示例(如果不是很复杂的应用,一般来讲是不会分模块的):


export default {
state: {},
getters: {},
mutations: {},
actions: {}
};

index.js示例(组装vuex):


import vue from 'vue';
import vuex from 'vuex';
import state from './state.js';
import * as getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';