Vuex模块化

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

因此,Vuex 允许我们将 store 分割成模块(module),每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的,这样使得多个模块能够对同一 mutation 或 action 作出响应。如果希望你的模块具有更高的封装度和复用性,此时就用到了命名空间这个概念。

Vuex模块引入操作:
在这里插入图片描述
about.vue

<template>
  <div class="about">

    <h1 @click="setMallname('Green')">{{mall.mallname}}</h1>
    <h1 @click="setLuntanname('Gluntan')">{{luntanname}}</h1>

  </div>
</template>

<script>
import { mapState,mapGetters, mapActions, mapMutations } from 'vuex'

export default{
  mounted(){
      console.log(this); 
      //触发vuex的action方法
      // this.$store.dispatch('getJoke')
      // this.getJoke()
    },
    methods:{
      // addAge:function(){
      //   this.$store.commit('addAge', 3)
      // }
      ...mapActions(['getJoke']),
      ...mapMutations(['addAge','getList','setMallname']),
      ...mapMutations('luntan',['setLuntanname'])  //设置命名空间后,引入方式有所不同。
    },
    computed:{
      ...mapState(['mall']), //结构mapState
      ...mapState('luntan',['luntanname'])
    }
}
</script>

设置命名空间后,引入方式有所不同。…mapMutations(‘luntan’,[‘setLuntanname’]) 先导入luntan名称,然后设置引入属性

luntan.js

export default {
    namespaced:true,
    state : {
        luntanname:"格林lt"
    },
    mutations:{
        setLuntanname:function(state,payload){
            state.luntanname = payload
        }
    }
}

index.js

import luntan from './luntan'
 modules: {
    luntan
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值