App.vue点击异步计算按钮进行异步操作通过 store.dispatch 方法触发Action:
<template>
<div id="app">
<button @click="addCount">同步计算</button>
<br>
<br>
<button @click="addCountAsyn">异步计算</button>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
}
},
components: {
},
methods: {
addCount() {
// 第一个参数:mutations中声明的函数名;第二个参数:要传递的数据
// this.$store.commit('addCount', 5);
// 第1种方式传入额外的参数,mutations中使用载荷payload
// this.$store.commit('addCount', {num: 5});
// 第2种方式传入额外的参数
this.$store.commit({
type: 'addCount',
num: 5
})
},
addCountAsyn() {
// this.$store.commit('addCountAsyn', 10);
this.$store.dispatch('addCountAsyn', {num: 10});
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
index.js种Action调用commit提交一个mutation:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
Vue.config.devtools = true
export default new Vuex.Store({
state: {
count: 10
},
mutations: {
// payload载荷获取传入的额外参数
addCount(state, payload) {
state.count += payload.num;
},
// 不要在这里异步操作,devtools监测不到属性值的变化
// addCountAsyn(state, num) {
// setTimeout(() => {
// state.count += num;
// }, 1000);
// }
addCount2(state, num) {
state.count += num;
},
},
actions: {
addCountAsyn({ commit }, payload) {
setTimeout(() => {
commit('addCount2', payload.num);
}, 1000);
}
},
modules: {
}
})
页面效果: