总结
写法
// 创建store文件夹 然后在store文件夹下创建对应的js文件
// 在该js文件中引入对应的依赖文件
import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from 'moduleA所在的文件的地址'
import moduleB from 'moduleB所在的文件的地址'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
moduleA
}
})
export default store
// 在main.js中引入store
import store from '对应的主js文件地址'
new Vue({
store
})
// 创建模块a的文件 例如该项目中的moduleA.js
const moduleA = {
state: {
data1: {}
},
getters: {
getData(state, getters, rootState, rootGetters) {
// state 本模块的state
// getters 本模块的getters
// rootState 所有模块的数据集合
// rootGetters 所有模块的getters的集合
}
},
mutations: {
mutationFun(state, data) {
// state 本模块的state
// data 调用函数时传递的参数
}
},
actions: {
actionFun({dispatch, commit, getters, state, rootGetters, rootState}) {
// actions中的函数有一个默认参数 context 这个函数可以进行解构
// context: {dispatch: function() , commit:function(), getters: function(), state: state, rootGetters: function(), rootState}
// dispatch调用actions函数的方法
// commit 提交mutations函数的方法
// getters 是本模块的getter函数
// state 本模块的state数据
// rootGetters 所有模块的getters属性集合
// rootState 所有模块的数据集合
}
}
}
// 创建模块b的文件 例如 该项目中的 moduleB.js
const moduleB = {
state: {
data2: {}
},
getters: {
getData2() {
}
},
mutations: {},
actions: {}
}
用法
- 在对应的vue文件中
<template>
<div>
{{moduleA.data1}}
{{moduleB.data2}}
{{getData}}
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'
export default {
name: '',
data() {
return {}
},
computed: {
...mapState(
[
'moduleA',
'moduleB'
]),
// 模块之间的getters方法名称不能同名
...mapGetters([
'getData',
'getData2'
])
},
created() {
// this.$store.commit('函数名', '要传递的参数') 这两种形式的调用和传参的方式叫做载荷
// this.$store.dispatch('函数名', '要传递的参数')
this.mutationFun('可以传递参数')
this.actionFun('可以传递参数')
},
methods: {
...mapMutations([
'mutationFun'
]),
...mapActions([
'actionFun'
])
}
}
</script>
<style scoped>
</style>