54

有人能解释一下你什么时候会使用调度和提交吗?

我知道提交会触发突变,而分派会触发动作。

但是,调度不也是一种动作吗?

4

1 回答 1

136

正如你所说的,$dispatch触发一个动作,并commit触发一个突变。以下是如何使用这些概念:

你总是$dispatch在路由/组件中使用你的方法。$dispatch向您的 vuex 商店发送消息以执行某些操作。该操作可以在当前 tick之后的任何时间执行,这样您的前端性能不会受到影响。

您永远不会commit来自任何组件/路线。它在操作中完成,并且在您有一些数据要提交时完成。原因:提交是同步的,可能会冻结你的前端直到它完成。

让我们考虑这种情况:如果您必须从服务器获取一些 json 数据。在这种情况下,您需要异步执行此操作,以便您的用户界面不会无响应/冻结一段时间。所以,你只是$dispatch一个动作,并期望它稍后完成。您的操作会执行此任务,从服务器加载数据并稍后更新您的状态。

如果您需要知道某个操作何时完成,以便在此之前显示一个 ajax 微调器,您可以返回一个 Promise,如下所述(例如:加载当前用户):

以下是定义“loadCurrentUser”操作的方法:

actions: {
    loadCurrentUser(context) {
        // Return a promise so that calling method may show an AJAX spinner gif till this is done
        return new Promise((resolve, reject) => {
            // Load data from server
            // Note: you cannot commit here, the data is not available yet
            this.$http.get("/api/current-user").then(response => {
                // The data is available now. Finally we can commit something
                context.commit("saveCurrentUser", response.body)  // ref: vue-resource docs
                // Now resolve the promise
                resolve()
            }, response => {
                // error in loading data
                reject()
            })
        })
    },
    // More actions
}

在您的突变处理程序中,您执行源自操作的所有提交。以下是定义“saveCurrentUser”提交的方式:

mutations: {
    saveCurrentUser(state, data) {
        Vue.set(state, "currentUser", data)
    },
    // More commit-handlers (mutations)
}

在您的组件中,当它是createdor时mounted,您只需调用如下所示的操作:

mounted: function() {
    // This component just got created. Lets fetch some data here using an action
    // TODO: show ajax spinner before dispatching this action
    this.$store.dispatch("loadCurrentUser").then(response => {
        console.log("Got some data, now lets show something in this component")
        // TODO: stop the ajax spinner, loading is done at this point.
    }, error => {
        console.error("Got nothing from server. Prompt user to check internet connection and try again")
    })
}

如上所示返回 Promise 完全是可选的,也是并非所有人都喜欢的设计决策。有关是否返回 Promise 的详细讨论,您可以阅读此答案下的评论:https ://stackoverflow.com/a/40167499/654825

于 2016-11-03T04:09:27.230 回答