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>

猜你喜欢

转载自blog.csdn.net/weixin_40119412/article/details/107595740
5-1
今日推荐