什么是 Vuex Actions?
在 Vuex 中, Actions 是调用 mutations 的函数。 Actions 之所以存在,是因为 mutations 必须 是同步 的,而 Actions 可以是异步的。
您可以通过将 POJO 作为 actions
属性添加到 Vuex 存储 构造函数,如下所示。 要调用一个Actions,你应该使用 Store#dispatch()
功能 。
const Vuex = require('vuex');
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => ++state.count
},
actions: {
incrementDelay: async function(context) {
// Wait 50ms
await new Promise(resolve => setTimeout(resolve, 50));
context.commit('increment');
}
}
});
// To "call" an action, you should use call `dispatch()` function with
// the action's name.
await store.dispatch('incrementDelay');
store.state.count; // 1
Actions 的要点是什么?
关于 Actions,最明显的问题是 为什么要用 Actions?Vuex 商店有一个 commit()
允许任何函数 提交突变的函数,所以你可以很容易地做到这一点:
const Vuex = require('vuex');
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => ++state.count
}
});
async function incrementDelay() {
// Wait 50ms
await new Promise(resolve => setTimeout(resolve, 50));
store.commit('increment');
}
// Instead of dispatching an action, you could just call an
// async function.
await incrementDelay();
store.state.count; // 1
单独来看,上面的异步函数方法更好,因为它不依赖于任何特定的框架。 您可以只调用一个函数,仅此而已。 另外你可以使用 incrementDelay()
作为 Vue 实例上的方法并免费获得 错误处理 。
但是使用Actions有一个很酷的好处: subscribeAction
应用程序接口 。 Vue 允许您注册一个 回调 ,每次调度一个Actions时 Vue 都会调用该回调。
const Vuex = require('vuex');
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => ++state.count
},
actions: {
incrementDelay: async function(context) {
// Wait 50ms
await new Promise(resolve => setTimeout(resolve, 50));
context.commit('increment');
}
}
});
store.subscribeAction(function callback(action, state) {
// Prints "{ type: 'incrementDelay', payload: undefined }"
console.log(action);
});
// To "call" an action, you should use call `dispatch()` function with
// the action's name.
await store.dispatch('incrementDelay');
store.state.count; // 1
这 subscribeAction()
API 是很多 Vuex 插件 的基础,所以使用 action 可以让你更好地利用 Vue 社区的插件。
mapActions()
Actions 很棒,但是如何将它们与 Vue 组件一起使用呢? Vuex 有一个整洁的 mapActions()
将操作转换为 Vue 实例方法的函数 ,如下所示。
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => ++state.count
},
getters: {
count: state => state.count
},
actions: {
incrementDelay: async function(context) {
// Wait 50ms
await new Promise(resolve => setTimeout(resolve, 50));
context.commit('increment');
}
}
});
const app = new Vue({
store,
methods: Vuex.mapActions(['incrementDelay']),
computed: Vuex.mapGetters(['count']),
mounted: async function() {
await this.incrementDelay(); // Dispatches "incrementDelay"
},
// Displays 0, then 1 after 50ms
template: `<h1>{{count}}</h1>`
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论