vuex中module的命名空間概念

  • 默認情況下,模塊內部的 action、mutation 和 getter 是注冊在全局命名空間的。

    • 弊端1:不同模塊中有相同命名的mutations、actions時,不同模塊對同一 mutation 或 action 作出響應。
    • 弊端2:當一個項目中store分了很多模塊的時候,在使用輔助函數mapState、mapGetters、mapMutations、mapActions時,很難查詢,引用的state、getters、mutations、actions來自於哪個模塊,不便於后期維護。
  • 可以通過添加 namespaced: true 的方式使其成為帶命名空間的模塊。當模塊被注冊后,它的所有 getter、action 及 mutation 都會自動根據模塊注冊的路徑調整命名。

    1. 在模塊中添加 namespaced: true, 開始命名空間

    2. 在根store中引入模塊並掛載

    3. 組件中使用模塊中定義的“permissionList” state

      • 第一種方式

        1. // 1. 導入輔助函數mapState
        2. import { mapState } from "vuex";
        3. export default {
        4. props: {
        5. data: {
        6. type: Object,
        7. default: "chart"
        8. }
        9. },
        10. data() {
        11. return {
        12. list: {}
        13. };
        14. },
        15. computed: {
        16. //2. 在輔助函數mapState的第一參數上,填寫上模塊的命名空間名。根據掛載方式不同,此處的命名空間名就是 wechatType 或 aaa。
        17. ...mapState('命名空間名', ["permissionList"])
        18. },
      • 第二種方式

        1. //通過使用 createNamespacedHelpers 創建基於某個命名空間輔助函數。
        2. //它返回一個對象,對象里有新的綁定在給定命名空間值上的組件綁定輔助函數
        3. import { createNamespacedHelpers } from "vuex";
        4. const { mapState } = createNamespacedHelpers('命名空間名')
        5. export default {
        6. computed: {
        7. ...mapState(["permissionList"])
        8. }