美文网首页
vuex中modules的使用

vuex中modules的使用

作者: 波仔_4867 | 来源:发表于2021-04-01 16:57 被阅读0次

    一、什么时间使用modules

    由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

    为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
    在模块中使用:namespaced: true, 命名空间,添加之后,当前模块下的标识符可以和其它模块相同,用于解决不同模块的命名冲突问题

       //但是注意:使用命名空间后,
       //读取user模块getter 数据要用对象的形式,因为它需要命名
                      ...mapGetters({getlist:'user/getlist'})
    

    二、在store中定义modules

    const moduleA = {
                state: () => ({ ... }),
                mutations: { ... },
                actions: { ... },
                getters: { ... }
            }
    
            const moduleB = {
                state: () => ({ ... }),
                mutations: { ... },
                actions: { ... }
            }
    
            const store = new Vuex.Store({
                modules: {
                    a: moduleA,
                    b: moduleB
                }
            })
    
            store.state.a // -> moduleA 的状态
            store.state.b // -> moduleB 的状态
            //每个模块都有自己的state, mutations, actions, getters,modules
    

    三、在组件中使用

                读取: 
                    主模块: this.$store.state.msg
                    a模块:  this.$store.state.a.msg
                修改
                    主模块: this.$store.commit('change',参数)
                    a模块: this.$store.commit('a/change',参数)
                 //不论是修改还是读取数据名或函数名前都要加上模块名
    

    四、结合辅助函数使用

                  //  初始化执行actions里的 getdata函数
                    created(){
                        this['order/getdata']()
                     },
                    computed: {
                        //读取主模块数据
                        ...mapState(['msg'])
                      //读取user模块数据
                        ...mapState({
                            username: state=>state.user.username
                        })
                        //读取user模块getter 数据
                      ...mapGetters({getlist:'user/getlist'})
                    },
                    methods: {
                        ...mapMutations([
                            'user/changeUser',
                            'changeMsg'
                        ]),
                         ...mapActions(['order/getdata']),
                      //点击事件触发mutations 里的changeUser函数
                        change2(){
                            this["user/changeUser"]('Amy')
                        }
                    }
    

    相关文章

      网友评论

          本文标题:vuex中modules的使用

          本文链接:https://www.haomeiwen.com/subject/dtgtkltx.html