【Vue2】Vuex MapState 用法
mapState 基本用法
mapState 是 State 的延伸用法,當你的 State 越來越多時,可以用 mapState 來簡化,我們先來看如果沒用 mapState 會是怎麼樣:
<script>
  export default {
    computed: {
      count () {
        return this.$store.state.count;
        },
      count2 () {
        return this.$store.state.count2;
      },
      count3 () {
        return this.$store.state.count3;
      }
      ...
    }
  }
</script>
可以想像如果今天是一個大專案有超多 State 寫起來就會很耗費時間,所以有了 mapState 來解決這個問題。來看看改寫後的樣子:
<script>
  import { mapState } from "vuex";
  export default {
    computed: mapState(['count','count2','count3',...]),
  };
</script>
一行就解決!寫起來輕鬆很多吧~
mapState 會回傳一個物件,然後去 map 陣列裡的字串去找出符合的變數。
那有時候 computed() 裡面不只有 store 的變數,這時候就可以用 Spread syntax(展開運算子) 來擴展 mapState 回傳的物件。
<script>
  import { mapState } from "vuex";
  export default {
    computed: {
      myTitle () {
        return 'My Title';
      },
    ...mapState(['count','count2','count3',...])
    },
  };
</script>
除了使用跟 store 相同的字串外,也可以自定義變數名稱,有兩種指定方式:
- 變數的名稱字串
 - 一般函式 or 箭頭函式回傳 state 變數
 
<script>
  import { mapState } from "vuex";
  export default {
    computed: {
      myTitle() {
        return "My Title";
      },
      ...mapState({
        customCount: "count", // 變數字串
        customCount2() {
          return state.count2;
        }, // 一般函式
        customCount3: (state) => state.count3, // 箭頭函式
      }),
    },
  };
</script>
mapState 搭配模組化
當專案越大時,會需要把不同功能的 State 拆分開來,像是管理 UI 的 State 或是可能一個頁面就一個 State,這時候就需要使用模組化組件的方式引入。
模組化組件引入會像是這樣:
store/index.js
const moduleA = {
  namespaced: true,
  state: () => ({ ... }),
  mutations: { ... },
};
const moduleB = {
  namespaced: true,
  state: () => ({ ... }),
  mutations: { ... },
};
export default new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
因為要分辨你使用的是哪一個 module,所以記得要加上 namespaced: true,這樣在 mapState 就可以指定特定的模組名稱來引入 State:
<script>
  import { mapState } from "vuex";
  export default {
    computed: {
      ...mapState('moduleA',['stateA',...]),
      ...mapState('moduleB',['stateB',...]),
    },
  };
</script>
可以試看看下面的範例,有兩個計數器就是使用 modules 分別用不同的 state 去儲存的。