Vuex(篇5-1)——modules中state

为甚么使用模块?

  • vues使用单一状态树,意味着很多状态都会交给Vuex来管理
  • 当应用变的非常复杂时,Store对象就可能变的相当臃肿
  • 为解决这个问题,Vuex允许我们将store分割成模块(Module),并且每个模块拥有自己的StateMutationActionsGetters

对于模块内部的 mutationgetter,接收的第一个参数是模块的局部状态对象

模块A

const state={   
	 count:1,    
	 hername:'JOHU'}
 const mutations={    
	 add (state){//state是局部的        
 	state.count++;   
  }}
  const actions={}
  const getters={    
 	 Aname (state) {        
 		 return 'moduleA'+state.count.toString()    
  }}
  export default {    
 	 namespaced:true,    
 	 state,    
 	 mutations,   
  	 actions,   
   	 getters
    }

模块B

export default{   
  namespaced: true,    
  state:{        
 	count:4,       
  	hisname:'ModubleB'   
   },   
  mutations:{        
    add (state){            
      state.count++;       
    }    
  },   
  getters:{        
      Bname (state) {           
       return 'Aname'+state.hisname.toString()        
       }    
}}

全局index.js

import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from '@/vuex/module/modulea.js'
import moduleB from '@/vuex/module/moduleb.js'
Vue.use(Vuex)
const store = new Vuex.Store({   
state:{ 
      count:10,
 },  
 mutations:{ 
    add (state){        
    state.count++;    }   },   
 getters:{
        theirname(state){
            return 'them'+state.count.toString()       
           }
  },
  actions:{},   
 modules: {
        a:moduleA,       
        b:moduleB   
   }
   })
 export default store

组件中使用vuex中模块的state

方法1:直接使用属性this.$store.state

<p>moduleB中的:{{this.$store.state.moduleB.count}}</p>
<p>moduleA中的:{{this.$store.state.moduleA.count}}</p>
<p>全局中的:{{this.$store.state.count}}</p>
//当模块使用别名时
<p>moduleB中的:{{this.$store.state.b.count}}</p>
<p>moduleA中的:{{this.$store.state.a.count}}</p>
<p>全局中的:{{this.$store.state.count}}</p>

方法2:使用mapState辅助函数,映射到computed

 ...mapState({
            countA:state => state.a.count,
            countB:state => state.b.count,
            count: state => state.count
        })     
    <ul>
          <li>{{countA}}</li>
          <li>{{countB}}</li>
          <li>{{count}}</li>
      </ul>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值