vuexactions
Posted bgwhite
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vuexactions相关的知识,希望对你有一定的参考价值。
actions:既然mutations只能处理同步函数,我大js全靠‘异步回调’吃饭,怎么能没有异步,于是actions出现了...
actions和mutations的区别
1.Actions 提交的是 mutations,而不是直接变更状态。也就是说,actions会通过mutations,让mutations帮他提交数据的变更。
2.Action 可以包含任意异步操作。ajax、setTimeout、setInterval不在话下
![技术分享图片](file:///C:/Users/ADMINI~1/AppData/Local/Temp/enhtmlclip/a.gif)
两秒后年龄增加
![技术分享图片](https://image.cha138.com/20210808/b3cbdc78f3cc4b0d9d168e525565eda9.jpg)
看这样一段代码,大家就会明白他的使用:
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex); const store = new Vuex.Store({ state: { age: 18, }, mutations: { add: function (state,value) { state.age += value; } }, getters: { age: function (state) { return state.age; } }, actions: { addAsync: function (context,value) { setTimeout(function(){ context.commit(‘add‘,value); },2000) } } }); export default store
上述代码中mutations先定义一个方法add方法,然后再actions中异步操作,调用mutations中的方法,间接操作state中的数据。
<template> <div @click="add" class="age">+{{age}}</div> </template> <script> import store from ‘../../../utils/store‘; export default { components: { }, data () { return { } }, computed: { age: function () { return store.getters.age; } }, methods: { add: function () { store.dispatch(‘addAsync‘,5) } }, } </script> <style scoped> .age { width: 100rpx; height: 90rpx; line-height: 90rpx; border: 1rpx solid #ccc; } </style>
上述代码中computed中的add为获取vuex中的数据,然后再methods中异步增加年龄。
以上是关于vuexactions的主要内容,如果未能解决你的问题,请参考以下文章
Vuex Action - 返回 Axios Promise