- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此可以调用 context.commit
提交一个 mutation,或者通过 context.state
和 context.getters
来获取 state 和 getters。
通过action异步操作,以及传参
分发 Action
Action 通过 store.dispatch
方法触发:
store.dispatch('increment')
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
action的具体用法:
如实现组件productListOne中,实现三秒后点击button按钮降价:
// store.js中
mutations:{
reducePrice: (state) => {
setTimeout(function () {
state.products.forEach(product => {
product.price -= 1;
});
},3000)
}
}
// 但是以上写法,点击商品降价,控制台出现事件函数,但是价格在三秒后才发生变化,如果点击多次,方法触发很多次了,但是才会慢慢发生变化,这样并不利于调试。
因此,要想mutations中的 函数实现异步操作,需要用到action,将需要异步执行的函数,下在actions里面;
// store.js
mutations:{
reducePrice: (state) => {
// setTimeout(function () {
state.products.forEach(product => {
product.price -= 1;
});
// },3000)
}
},
actions:{
reducePrice:(context) => {
setTimeout(function () {
context.commit("reducePrice"); // 此处的context类似于store
},3000)
}
}
// productListOne.vue中
methods: {
reducePrice: function(){
// this.$store.state.products.forEach(product => {
// product.price -= 1;
// });
// this.$store.commit('reducePrice')
this.$store.dispatch("reducePrice") // 要想走action里的方法,此刻就需要dispatch
}
}
同时,这样的写法还可以传参,实现点击商品降价,每点击一次降价4元,<button @click="reducePrice(4)">商品降价</button>,参数由reducePrice: function(amount){}中的amount接收,通过this.$store.dispatch("reducePrice",amount)传递给store.js;store.js中的action通过reducePrice:(context,payload) => {} 中的payload接收;同时mutation中也需要接收payload, reducePrice: (state,payload) => {}
如下代码:
// productListOne.vue中
<template>
<div id="product-list-one">
<h2>Product-List-One</h2>
<ul>
<li v-for="product in saleProducts">
<span class="name">{{product.name}}</span>
<span class="price">${{product.price}}</span>
</li>
</ul>
// <button @click="reducePrice">商品降价</button>
<button @click="reducePrice(4)">商品降价</button>
</div>
</template>
<script>
methods: {
reducePrice: function(amount){ // amount形参
// this.$store.state.products.forEach(product => {
// product.price -= 1;
// });
// this.$store.commit('reducePrice')
this.$store.dispatch("reducePrice",amount) // store.js中通过payload接收amount
}
}
</script>
// store.js
mutations:{
reducePrice: (state,payload) => { // 接收payload
// setTimeout(function () {
state.products.forEach(product => {
// product.price -=1;
product.price -= payload;
});
// },3000)
}
},
actions:{
reducePrice:(context,payload) => {
setTimeout(function () {
context.commit("reducePrice",payload); // payload接收dispatch传过来的amount,再传给mutation
},3000)
}
}
以上就是通过action异步操作mutations里的函数及传参。