vuex模块中的state,getters,mutations,actions调用

模块化的方法

  1. 在./src目录下新建store目录新建index.js 【./src/store/index.js】,在./src/main.js中import,import store from './store'
import Vue from "vue";
import Vuex from "vuex";

import yqfk from "./yqfk";
Vue.use(Vuex);
const state = {};
const mutations = {};
const actions = {};
export default new Vuex.Store({
  state,
  mutations,
  actions,
  modules: {
    yqfk
  }
});
  1. 在上述store目录下,新建yqfk.js【./src/store/yqfk.js】,导出,在index.js中导入到modules字段中
const state = {
  test:1
};
const getters = {
	testGetter(state){
		return state.test
	}
}
const mutations ={

}
const actions = {

}
export default {
  namespaced:true,
  state,
  getters,
  mutations,
  actions,
}
  1. 在vue单页中使用
  • state:【this.$store.state.模块名.key】
  • getters:【this.$store.getters[‘模块名/key’]】
  • mutations:【this.$store.commit(‘模块名/method’)】
  • actions:【this.$store.dispatch(‘模块名/method’)】
<script>
export default {
  name: "Home",
  computed:{
    test(){
      return this.$store.state.yqfk.test
	},
	getTest(){
		return this.$store.geters['yqfk/testGetter']
	}
  }
};
</script>

4.mapState,mapGetters,mapMutations,mapActions 使用

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

export default {
  name: "Home",
  computed:{
  // 两种取模块中的state值的方法
  	...mapState({
  		test:state => state.yqfk.test
  	}),
 	...mapState('yqfk',{
 		test:state => state.test
 	}), 
   ...mapGetters('yqfk',{
   		getTest: 'testGetter'
   })
  }
};
</script>
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值