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'])