index.js:(store入口)
import Vue from 'vue' import Vuex from 'vuex' import setting from "./modules/setting" import user from "./modules/user" import getters from "./getters"; Vue.use(Vuex) const store = new Vuex.Store({ modules: { setting, user }, getters }) export default store
getters.js:(通常可以将所有的getters放在外面方便获取;当然也可以写在modules下面js内部)
const getters={ index:state=>state.setting.index } export default getters
setting.js
const state = { index:0 } const mutations = { changeIndex_mutation(state, n) { /* n为角标 */ state.index = n }, hideIndex_mutation(state, n) { state.index = n } } const actions = { changeIndex(context, n) { context.commit('changeIndex_mutation', n) }, hideIndex(context, n) { context.commit('hideIndex_mutation', n) } } // const getters = { //我们将所有的getters放到外面去 // getStateIndex(state) { // return state.index // } // } export default { namespaced: true, //命名可重复 state, mutations, actions, // getters }
user.js(这里啥也没写,只做参考)
const state = { } const mutations = { } const actions = { } const getters = { } export default { namespaced: true, //命名可重复 state, mutations, actions, getters }
vue文件:
1:vueX_test.vue
<template> <div class=""> <span class="ys-btn" @click="showIt(0)">显示蓝色的</span> <span class="ys-btn" @click="showIt(1)">显示红色的</span> <span class="ys-btn" @click="showIt(2)">显示黑色的</span> <span class="ys-btn" @click="removeAll(-1)">一个都不显示</span> </div> </template> <script> import {mapActions} from 'vuex'; export default { name: "vueX_test", data(){ return{ } }, mounted(){ }, methods:{ // ...mapActions(['changeIndex','hideIndex']), // 未使用 namespaced: true, //命名可重复 // showIt(i){ //这样传参 // this.changeIndex(i) // }, // removeAll(i){ //这样传参 // this.hideIndex(i) // } ...mapActions('setting',['changeIndex','hideIndex']), showIt(i){ //这样传参 this.changeIndex(i) }, removeAll(i){ //这样传参 this.hideIndex(i) } } } </script>
2:vueX_test2.vue
<template> <div class=""> <div class="ys-bg ys-bg-blue" :class="{'on':index==0}">1111</div> <div class="ys-bg ys-bg-red" :class="{'on':index==1}">222</div> <div class="ys-bg ys-bg-black" :class="{'on':index==2}">333</div> </div> </template> <script> import{mapState,mapGetters,mapActions} from 'vuex'; export default { name: "vueX_test", data(){ return{ index:this.$store.getters.index //或者使用mapState } }, // computed:{ // ...mapState({ // index:state=>state.setting.index // }) // } } </script> <style> .ys-bg{ display: none; height:300px; } .ys-bg.on{ display: block; } </style>
注:
1:由上可见namespaced: true后 命名可重复,但是对应函数也变成局部函数,无法直接获取,需要设置对应文件路径;
2:... 是es6的展开运算符;mapAction返回数组对象(['c,'d']);将其直接结构到当前组数对象中;(['a','b',...mapAction]===['a','b','c','d'])