- store/index.js
【sumOptions、newsOptions分文件存放,并利用modules配置项将其模块化】import Vue from 'vue';
import Vuex from 'vuex';
import sumOptions from './sum';
import newsOptions from './news';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
sumOptions,
newsOptions
}
});
- store/sum.js
export default {
namespaced: true,
state: {
sum: 0
},
actions: {
addNumGt5(context, value) {
if (context.state.sum > 5) {
context.commit('addNum', value);
}
}
},
mutations: {
addNum(state, value) {
state.sum += value;
}
},
getters: {
addPrefix(state) {
return '@' + state.sum;
}
}
}
- store/news.js
export default {
namespaced: true,
state: {
title: '新闻标题',
content: '新闻内容'
},
actions: {},
mutations: {},
getters: {
getInfo(state) {
return state.title + ',' + state.content;
}
}
}
- 以Count组件举例使用vuex中的状态
<template>
<div>
<p>总和为:{{sum}}</p>
<button @click="addNum(addend)">+</button>
<button @click="addNumGt5(addend)">总和>5才+</button>
<p>{{addPrefix}}</p>
</div>
</template>
<script>
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex';
export default {
name: 'Count',
data() {
return {
addend: 1
}
},
computed: {
sum() {
return this.$store.state.sumOptions.sum;
},
...mapState('sumOptions', ['sum']),
addPrefix() {
return this.$store.getters['sumOptions/addPrefix'];
},
...mapGetters('sumOptions', ['addPrefix']),
},
methods: {
addNumGt5() {
this.$store.dispatch('sumOptions/addNumGt5', this.addend);
},
...mapActions('sumOptions', ['addNumGt5']),
addNum() {
this.$store.commit('sumOptions/addNum', this.addend);
},
...mapMutations('sumOptions', ['addNum'])
}
}
</script>