1. 程式人生 > >基於vue-cli的vue專案之vuex的使用3-------action非同步傳參

基於vue-cli的vue專案之vuex的使用3-------action非同步傳參

由於使用commit是同步的,所以也就有了使用“非同步”的action的誕生

1.store.js//配置倉庫第十五行到第二十三行配置action,
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		count: 0
	},
	mutations: {
		increment(state, n) {
			console.log(n);
			state.count += n.amout;
		}
	},
	actions: {
		increment(context, m) {
			setTimeout(() => {
				context.commit({
					type: "increment",
					amout: m.amout
				})
			}, 1000)
		}
	}

})
//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//在元件中使用//在第六十七行到第七十二行使用dispatch去提交
<template>
	<div id="app">
		<img src="./assets/logo.png">
		<button @click="clickme">點選呼叫commit</button>
		<button @click="clickme1">點選呼叫dispatch</button>
		<span>{{$store.state.count}}</span>
	</div>
</template>
<script>
	export default {
		name: 'app',
		data() {},
		methods: {
			clickme: function() {
				this.$store.commit({
					type: "increment",
					amout: 180
				});
				console.log(this.$store.state.count);
			},
			clickme1: function() {
				this.$store.dispatch({
					type: "increment",
					amout: 180,
				});
			}
		},
	}
</script>
<style>
</style>