接上文
一个简单的例子 vux mutation改变状态
D:\workspace\xxx\src\main.js
定义actions
let store = new Vuex.Store({ state: { totalPrice: 0 }, mutations: { increment (state, price) { state.totalPrice += price }, decrement (state, price) { state.totalPrice -= price } }, // actions是mutations之前的动作,只能调用mutations actions: { increase (context, price) { context.commit('increment', price) } } })
D:\workspace\xxx\src\components\Apple.vue
就可以使用用.dispatch('increase', this.price)方法,间接操作mutations
与mutations的区别是actions是异步的。
<template> <div> <h1 >{{ msg }}</h1> <button @click="addOne">addOne</button> <button @click="minusOne">minusOne</button> <router-view/> </div> </template> <script> export default { name: 'Apple', data () { return { msg: 'I am an apple', price: 5 } }, methods: { addOne () { // this.$store.commit('increment', this.price) this.$store.dispatch('increase', this.price) }, minusOne () { this.$store.commit('decrement', this.price) } } } </script>
例如这种情况只能用actions
https://github.com/vuejs/vuex