store.js中声明Mutations中的方法:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
Vue.config.devtools = true
export default new Vuex.Store({
state: {
count: 10
},
mutations: {
addCount(state, num) {
state.count += num;
},
// payload载荷获取传入的额外参数
// addCount(state, payload) {
// state.count += payload.num;
// },
// 不要在这里异步操作,devtools监测不到属性值的变化
addCountAsyn(state, num) {
setTimeout(() => {
state.count += num;
}, 1000);
}
}
})
App.vue使用this.$store.commit调用Mutations中的方法:
<template>
<div id="app">
<!-- <button @click="countHandler">计算</button> -->
<button @click="addCount">同步计算</button>
<br>
<br>
<button @click="addCountAsyn">异步计算</button>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
}
},
components: {
},
methods: {
// countHandler() {
// // state默认只有getters,不能使用下面这种操作,修改状态的唯一方法是提交mutation
// this.$store.state.count ++ ;
// },
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);
}
}
}
</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>
页面效果: