vuex中module裏面的數據操作總結

Vuex 使用了 module 後的訪問方法:

01 - 如果 使用了 module 和 namespace

state 數據:=> this.$store.state.User.info (user 是模塊名字. info 是 state 裏面的屬性名字)

getters 數據: => this.$store.getters[‘User/getUserInfo’] (user namespace,模塊名, getUserInfo 是 getter 的名字)

mutations => this.$store.commit( ‘AppKeepAlive/remove’, name); (AppKeepAlive 模塊名, remove方法名, name 是荷載數據 payload)

在這裏插入圖片描述
02 - 使用語法糖調用

詳情可查看:https://www.jianshu.com/p/83d5677b0928

02-1 – mapState的使用

// ...
computed: {
    ...mapState({
        name: state => state.moduleA.text
    }),
},
// ...

02-2 – 訪問根節點state數據
我們已經知曉,模塊內部的 state 是局部的,只屬於模塊本身所有。那麼如果我們要想在模塊中訪問 store 根節點的數據 state,怎麼辦呢?編輯modelA.js如下:

export default {
    // module中存在rootState這個參數可以獲取根節點的數據
    getters: {
        // 注意: rootState必須是第三個參數
        detail(state, getters, rootState) {
            return state.text + '-' + rootState.name;
        }
    },
    actions: {
        callAction({state, rootState}) {
            alert(state.text + '-' + rootState.name);
        }
    }
}

然後在xxx.vue組件文件中調用:

<script>
    import {mapActions, mapGetters} from 'vuex';
    export default {
        computed: {
            ...mapGetters({
                name: 'detail'
            }),
        },
        methods: {
            ...mapActions(['callAction']),
            modifyNameAction() {
                this.callAction();
            }
        },
    }
</script>

02-3 通過添加 namespaced: true 的方式使其成爲帶命名空間的模塊
然後運行報錯,找不到getter detail

[vuex] unknown getter: detail```js

在全局 getter 中已經找不到 detail 的這個方法了,因爲它的路勁已經改變了,不再屬於全局,僅僅只屬於 moduleA 了。所以,這個時候,如果我們想要訪問它,必須帶上路勁纔行。修改 xxx.vue 如下:

<script>
    import {mapActions, mapGetters} from 'vuex';
    export default {
        computed: {
            ...mapGetters({
                name: 'moduleA/detail'
            }),
        },
        methods: {
            ...mapActions({
                call: 'moduleA/callAction'
            }),
            modifyNameAction() {
                this.call();
            }
        },
    }
</script>

注意,如果一個模塊啓用了命名空間,那麼它裏面的 getter 和 action 中收到的 getter,dispatch 和 commit 也都是局部化的,不需要在同一模塊內額外添加空間名前綴。也就是說,更改 namespaced 屬性後不需要修改模塊內的任何代碼。
優雅的寫法,語法糖實現:

computed: {
    ...mapState({
        a: state => state.some.nested.module.a,
        b: state => state.some.nested.module.b
    })
},
methods: {
    ...mapActions([
        // -> this['some/nested/module/foo']()
        'some/nested/module/foo', 
        // -> this['some/nested/module/bar']()
        'some/nested/module/bar' 
    ])
}

核心知識點

  • 模塊內部的 state 是局部的,只屬於模塊本身所有。
  • 模塊內部的 action、mutation 和 getter 默認是註冊在全局命名空間的
  • 如果我們只想讓他們在當前的模塊中生效,應該怎麼辦呢?-- 通過添加 namespaced: true 的方式使其成爲帶命名空間的模塊。
	export default {
	    namespaced: true,
	    // ...
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章