由于使用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>


Logo

前往低代码交流专区

更多推荐