vue —— vuex namespaced模块化编码

在需求过多的时候就会发生在actions mutations state getters 编写代码过多的情况会很混乱,可以把每个需求的代码进行分组 查看时便可根据不同的需求查看。不过在每个需求里还是要配置actions mutations state getters
使用方法

  • 在分组时 添加 namespaced: true 开启
  • 调用时
  • mapState(‘分组名’, [‘属性1’, ‘属性2’, ‘属性3’,……])
  • mapGetters(‘分组名’, [‘属性1’, ‘属性2’, ‘属性3’,……])
  • mapActions(‘分组名’, [‘方法1’, ‘方法2’, ‘方法3’,……])
  • mapMutations(‘分组名’, [‘方法1’, ‘方法2’, ‘方法3’,……])
注意export时使用modules

例如

// 求和相关的配置
const countOptions = {
	namespaced: true,
	actions: {
		jia: function(context,value){
			console.log('actions中的jia',context,value)
			context.commit('JIA',value)
		}
	},
	mutations: {
		JIA(state,value){
			console.log('mutations中的JIA',state,value)
			state.sum += value
		},
	},
	state: {
		sum: 0,
		school: '学校',
		subject: '学科',
	},
	getters: {
		bigSum(state){
			return state.sum*10
		}
	}
}
// 创建 暴露 store
export default new Vuex.Store({
	modules: {
		countAbout: countOptions,
	}
})
methods: {
	...mapActions('countAbout',['jia']),
},
computed:{
	...mapState('countAbout',['sum','school','subject']),
	...mapGetters('countAbout',['bigSum']),
}
<h1>{{sum}}h1>
<h1>{{school}}h1>
<h1>{{subject}}h1>
<h3>当前求和放大后为:{{bigSum}}h3>
<select v-model.number="n">
	<option value='1'>1option>
	<option value='2'>2option>
	<option value='3'>3option>
select>
<button @click='jia(n)'>+button>

不借助map……使用

  • this.$store.getters[‘分组名/方法名’]——获取getters的数据
  • this.$store.state.分组名.属性名——获取指定分组下的属性
  • this.$store.commit(‘分组名/方法名’, ‘参数’)——使用commit下的方法
  • this.$store.dispatch(‘分组名/方法名’, ‘参数’)——使用dispatch下的方法

你可能感兴趣的:(vue.js,前端,javascript)