Action 类似于 mutation,不同在于:
1、Action 提交的是 mutation,而不是直接变更状态。
2、Action 可以包含任意异步操作。
如果需要用到actions的情况,如下图,应该是组件调用Actions,Actions提交Mutations,Mutations修改state
定义
vuex 3 和 vue2
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
share:100
},
getters:{
shareFloat:function (state) {
return "¥" + state.share
}
},
mutations: {
addShare:function(state){
state.share++;
}
},
actions: {
//不是直接改变变量,而是提交mutations的函数
asyncAddShare:function(context,obj){
setTimeout(()=>{
//也可以通过 context.state 和 context.getters 来获取 state 和 getters
context.commit("addShare",obj)
},3000)
}
},
modules: {
}
})
vuex 4 和 vue3
src/store/index.js
import { createStore } from "vuex"
const store = createStore({
state() {
return {
counter: 100,
};
},
mutations: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
},
actions: {
// 放函数
// 1.简单使用,参数context可以调用mutations方法
incrementAction(context, n) {
console.log(n)
setTimeout(() => {
context.commit('increment')
}, 1000);
},
// 2.context的其他属性
// context = {commit, dispatch, state, rootState, getters, rootGetters}
decrementAction({ commit, dispatch, state, rootState, getters, rootGetters }) {
commit("decrement")
},
}
});
export default store;
参数 context
其他参数
打印看看
因此写法可以见上vuex 4 和 vue3,用一个对象{commit, dispatch, state, rootState, getters, rootGetters}代替context
commit:提交mutations的方法
dispatch:调用其他的actions方法
getters:使用vuex的计算属性getters
rootGetters、rootState :分模块的时候,拿到根仓库(最顶级数据仓库)的计算属性getters和数据state
state:数据仓库
使用
vuex 3 和 vue2 ,或vue3 选项api
在组件内使用$store.dispatch(“asyncAddShare”) 的方法使用actions的函数
<template>
<div>
test2
<el-button @click="add">add</el-button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
add:function () {
// 1、简单用法
// dispatch可以有第二个参数,就是定义那里的n,传入数据或对象等
this.$store.dispatch("incrementAction")
// 2、对象用法
this.$store.dispatch({
type:"incrementAction",
n:100
})
}
},
};
</script>
<style scoped>
</style>
vue3 组合api
<template>
<div>
test2
<el-button @click="add">add</el-button>
</div>
</template>
<script>
import {useStore} from 'vuex'
export default {
setup(){
const store = useStore()
const add = ()=>{
// 1、简单用法,参数用法和上面选项api一样
store.dispatch("incrementAction")
// 2、对象用法
store.dispatch({
type:"incrementAction",
n:100
})
}
return {
add
}
}
};
</script>
<style scoped>
</style>
网络请求
可以通过actions获取网络请求的数据,数据直接提交mutations修改对应的state
异步操作(返回Promise)
可以在定义actions函数时,返回Promise对象,后续其他地方使用时,可以通过then来接收执行状态
其他组件内使用,可以等actions执行完后再执行自定义的内容
Devtools
正确使用就会正常记录到devtools里面
批量使用 mapActions
选项API
数组写法和对象写法