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,
	    // ...
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章