基于vue-cli的vue项目之vuex的使用4-------moudles分块

按照官方文档,就是为了避免代码太长了。所以使用了moudle

1.store.js//配置仓库,第五道第二十六为一个模块。第二十七到四十八为一个模块,在第四十九到五十四行抛出
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const moudlesa = {
	namespaced:true,
state: {
		count: 0
	},
	mutations: {
		incrementa(state, n) {
			console.log(n);
			state.count += n.amout;
		}
	},
	actions: {
		incrementa(context, m) {
			setTimeout(() => {
				context.commit({
					type: "incrementa",
					amout: m.amout
				})
			}, 1000)
		}
	}
}
const moudlesb = {
	namespaced:true,
	state: {
		count: 0
	},
	mutations: {
		incrementb(state, n) {
			console.log(n);
			state.count += n.amout;
		}
	},
	actions: {
		incrementb(context, m) {
			setTimeout(() => {
				context.commit({
					type: "incrementb",
					amout: m.amout
				})
			}, 1000)
		}
	}
}
const store = new Vuex.Store({
	modules: {
		a: moudlesa,
		b: moudlesb

	}

})
//export default store;
export default store;

2.main.js//配置store的路径,在第六十九行使用store
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store';
Vue.config.productionTip = false;
new Vue({
	el: '#app',
	router,
	store,
	template: '<App/>',
	components: {
		App
	},
})

3app.vue//在组件中使用//在第九十到第九十六提交a模块的数据,第九十七到一百零二行提交b模块的数据
<template>
	<div id="app">
		<img src="./assets/logo.png">
		<button @click="clickme">点击调用commit</button>
		<button @click="clickme1">点击调用dispatch</button>
		<span>{{$store.state.a.count}}</span><span>{{$store.state.b.count}}</span>
	</div>
</template>
<script>
	export default {
		name: 'app',
		data() {},
		methods: {
			clickme: function() {
				this.$store.commit({
					type: "a/incrementa",
					amout: 180
				});
				alert(this.$store.state.a.count)
			},
			clickme1: function() {
				this.$store.dispatch({
					type: "b/incrementb",
					amout: 180,
				});
			}
		},
	}
</script>
<style>
</style>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值