1. 程式人生 > >基於vue-cli的vue專案之vuex的使用4-------moudles分塊

基於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>