目录
简介
说明
官网
actions概述
说明
特点
用法
示例
测试
简介
说明
本文用示例介绍Vuex的五大核心之一:actions。
官网
Action | Vuex
API 参考 | Vuex
actions概述
说明
Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
特点
1.异步操作,通过mutations来改变state。
2.不能直接改变state里的数据。
3.包含多个事件回调函数的对象。
4.执行方式:通过执行 commit()来触发 mutation 的调用, 间接更新 state
5.触发方式: 组件中: $store.dispatch(‘action 名称’, data1)
6.可以包含异步代码(例如:定时器, 请求后端接口)。
用法
直接使用
this.$store.dispatch('actions方法名', 具体值) // 不分模块
this.$store.dispatch('模块名/actions方法名', 具体值) // 分模块
mapActions
import { mapActions } from 'vuex'
export default {
computed: {
// 不分模块
...mapActions(['actions方法名'])
// 分模块,不改方法名
...mapActions('模块名', ['actions方法名'])
// 分模块,不改方法名
...mapActions('模块名',{'新actions方法名': '旧actions方法名'})
}
}
示例
CounterStore.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const counterStore = new Vuex.Store(
{
state: {
count: 10
},
getters: {
doubleCount(state) {
return state.count * 2;
}
},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
// 带参数
addNumber(state, param1) {
state.count += param1;
},
},
actions: {
asyncIncrement(context) {
console.log('CounterStore=> action: asyncIncrement');
setTimeout(() => {context.commit('increment')}, 1000)
},
asyncAddNumber(context, n) {
console.log('CounterStore=> action: asyncAddNumber');
setTimeout(() => {context.commit('addNumber', n)}, 1000)
}
}
}
);
export default counterStore;
Parent.vue(入口组件)
父组件
ComponentA.vue(异步修改vuex的数据)
ComponentA
ComponentB.vue(读取vuex的数据)
ComponentB
计数器的值:{{thisCount}}
计数器的2倍:{{thisDoubleCount}}
路由(router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/parent',
name: 'Parent',
component: Parent,
}
],
})
测试
访问: http://localhost:8080/#/parent
到此这篇关于Vuex中actions的使用教程详解的文章就介绍到这了,更多相关Vuex actions内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
vue中在vuex的actions中请求数据实例
Vuex的actions属性的具体使用
vuex actions传递多参数的处理方法
vuex中的 mapState,mapGetters,mapActions,mapMutations 的使用
详解vuex中mapState,mapGetters,mapMutations,mapActions的作用
vuex学习之Actions的用法详解
Vuex中actions优雅处理接口请求的方法
