一、拆分modules
在store下新建文件夹hooks,将拆分的模块放在此处

//CountHook.jsconst CountHook = {state: {count: 1},mutations: {},actions: {},/* 类似计算属性,可以对state中的值进行处理 */getters: {myCount(state) {return `当前的计数为:${state.count}`}}}export default CountHook;
二、 store/index.js中导入
import CountHook from './hooks/CountHook'export default new Vuex.Store({modules: {CountHook}})
三、使用
1-1 直接使用CountHook中的数据
<p>{{this.$store.state.CountHook.count}}</p>
1-2 mapState
<template><div class="home"><p>{{count}}</p></div></template><script>import {mapState} from 'vuex'export default {name: 'Home',computed:{...mapState({count:state=>state.CountHook.count})}}</script>
四、方法照常使用
<template><div class="home"><button @click="increase">{{count}}</button></div></template><script>import {mapState,mapMutations} from 'vuex'export default {name: 'Home',computed:{...mapState({count:state=>state.CountHook.count})},methods:{...mapMutations(["increase"])}}</script>
//CountHookconst CountHook = {state: {count: 1},mutations: {increase(state){state.count++}},actions: {},/* 类似计算属性,可以对state中的值进行处理 */getters: {myCount(state) {return `当前的计数为:${state.count}`}}}export default CountHook;
