vuexactions
时间: 2023-08-27 16:13:42 浏览: 66
在Vuex中,actions用于异步操作和触发mutations。actions接收两个参数,第一个参数是上下文(context),也可以称为Store,需要使用commit来触发函数。第二个参数可以是对象,传入多个属性。使用方法如下:
```
actions: {
changeP (ctx, addValue) {
setTimeout(() => {
ctx.commit('changePersonList', addValue); // 触发mutations中的changePersonList函数
}, 1000)
}
}
```
在使用actions时,可以在组件的created方法中调用该函数,如下所示:
```
created() {
this.$store.dispatch('buyNow', '要传递的参数')
}
```
还可以使用mapActions辅助函数,简化调用actions的写法,如下所示:
```
import {mapActions} from 'vuex'
created() {
this.buyNow().then(res => { console.log(res) })
},
methods: {
...mapActions([
'buyNow'
])
}
```
在Vuex中注册actions的写法如下:
```
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
// 购物车数据
shopCart: [
{ name: '卫龙大辣条', price: '¥1.25' },
{ name: '鱼豆腐', price: '¥2' }
]
},
getters: {},
mutations: {
// 改变购物车数据的函数
// 第一个参数state就是Store中的state
// 第二个参数是执行函数是 用户传递的数据
// 第三个参数用来判断是否清空购物车,如果是true则清空购物车
handleShopCart(state, data) {
state.shopCart = data
}
},
actions: {
buyNow({commit, state}) {
return new Promise((resolve, reject) => {
axios.get('购买按钮对应的请求地址')
.then(res => {
commit('handleShopCart', [])
resolve('这里是用户购买成功后要传递的数据')
})
.catch(err => {
commit('handleShopCart', state.shopCart)
reject('这里是用户购买失败后要传递的数据')
})
})
}
}
})
```
<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [vuex中的actions](https://blog.csdn.net/zyz00000000/article/details/88886343)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [vuexActions总结](https://blog.csdn.net/BL_gui/article/details/103989849)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)