
一、拆分modules
//count.jsconst count = { state: { count: 0 }, mutations: { increase(state) { state.count += 1; }, decrease(state) { state.count -= 1; } }, actions: { myIncrease(ctx) { ctx.commit("increase") }, myDecrease(ctx) { ctx.commit("decrease") } }, getters: { myCount(state) { return `当前计数为:${state.count}` } }}export default count;
//city.jsconst city = { state:{ defaultCity:"武汉" }}export default city;
二、store/index.js中导入
import Vue from 'vue'import Vuex from 'vuex'import city from './modules/city';import count from './modules/count';Vue.use(Vuex)export default new Vuex.Store({ modules: { city, count }})
三、使用
<template> <div class="home"> <h1>首页</h1> <h2>{{count}}</h2> <h3>{{myCount}}</h3> <h2>{{city}}</h2> </div></template><script>import {mapState,mapGetters} from 'vuex';export default { name: 'home', computed:{ ...mapState({ count:state=>state.count.count, city:state=>state.city.defaultCity }), ...mapGetters(['myCount']) }}</script>
3-1 方法照常使用
<template> <div class="about"> <h1>{{this.$store.state.count.count}}</h1> <button @click="add">增加</button> <button @click="reduce">减少</button> </div></template><script>import {mapActions} from 'vuex';export default { methods:{ ...mapActions(['myIncrease','myDecrease']), add(){ this.myIncrease() }, reduce(){ this.myDecrease() } }}</script>