对vuex数据流图加入了一些自己的理解内容
一、模块配置
目录结构
模块代码文件 moduleA.js
const state = {
"username": "foo",
"age": 18
}
const getters = {
// getAge(state) {
// return (n) => {
// return state.age += n;
// }
// }
getAge(state) {
return state.age + 10;
}
}
const mutations = {
setAge(state, n) {
state.age += n;
}
}
const actions = {
addCountDelay(context, n) {
setTimeout(function() {
context.commit('setAge', n)
}, 2000);
}
}
export default {
namespaced: true, // 开启命名空间支持
state,
getters,
mutations,
actions
}
index.js对模块文件的引用
import Vue from 'vue';
import Vuex from 'vuex';
import mA from '@/store/modules/moduleA.js'
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
moduleA: {
// namespaced : mA.namespaced,
// state : mA.state,
// getters : mA.getters,
// mutations : mA.mutations,
// actions : mA.actions
...mA
},
}
})
export default store;
二、state
获取state的值,如果在多模块的情况下可以用两种方式使用mapState
computed: {
// 第一种
...mapState('moduleA', ['username', 'age']),
// 第二种
...mapState({
username: (state) => state.moduleA.username,
age: (state) => state.moduleA.age
}),
}
三、getter
getter是store的计算属性,对state的加工,是派生出来的数据。
computed: {
getAge() {
// getters中加入了命名空间后对值的获取
return this.$store.getters["moduleA/getAge"];
}
}
在多模块中使用mapGetters
computed: {
...mapGetters('moduleA', ['getAge']),
})
}
四、mutation
mutation是唯一的修改state的方式,如果是同步方式可以直接从method中使用commit方法进行提交,跳过action内容,多模块中调用mutation中的方法
methods: {
setAge() {
this.$store.commit('moduleA/setAge', 26);
},
// ...mapMutations("moduleA", ['setAge']),
},
多模块中使用mapMutations
methods: {
...mapMutations("moduleA", ['setAge']),
},
五、action
action 提交的是 mutation
,通过 mutation
来改变 state
,而不是直接变更状态。action 可以包含任意异步操作。多模块中对action的使用
methods: {
addCountDelay() {
this.$store.dispatch('addCountDelay', 20);
}
},
多模块中对mapActions的使用
methods: {
...mapActions("moduleA", ['addCountDelay'])
},