Vuex 动作与突变 [英] Vuex Action vs Mutations

查看:28
本文介绍了Vuex 动作与突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Vuex 中,同时拥有actions"和mutations"的逻辑是什么?

In Vuex, what is the logic of having both "actions" and "mutations?"

我理解组件无法修改状态的逻辑(这看起来很聪明),但是同时具有动作和突变似乎你正在编写一个函数来触发另一个函数,然后改变状态.

I understand the logic of components not being able to modify state (which seems smart), but having both actions and mutations seems like you are writing one function to trigger another function, to then alter state.

动作"和突变"之间有什么区别,它们如何协同工作,此外,我很好奇为什么 Vuex 开发人员决定这样做?

What is the difference between "actions" and "mutations," how do they work together, and moreso, I'm curious why the Vuex developers decided to do it this way?

推荐答案

问题 1:为什么 Vuejs 开发人员决定这样做?

Question 1: Why the Vuejs developers decided to do it this way?

答案:

  1. 当您的应用程序变大,并且有多个开发人员在处理此项目时,您会发现状态管理"(尤其是全局状态"),将变得越来越复杂.
  2. vuex 方式(就像 react.js 中的 Redux)提供了一种管理状态的新机制,保持状态,以及保存和可跟踪"(这意味着可以通过 调试工具:vue-devtools 跟踪每个修改状态的操作)
  1. When your application becomes large, and when there are multiple developers working on this project, you will find the "state manage" (especially the "global state"), will become increasingly more complicated.
  2. The vuex way (just like Redux in react.js) offers a new mechanism to manage state, keep state, and "save and trackable" (that means every action which modifies state can be tracked by debug tool:vue-devtools)

问题 2:action"和action"有什么区别?和突变"?

Question 2: What's the difference between "action" and "mutation"?

先看官方解释:

突变:

Vuex 突变本质上是事件:每个突变都有一个名称和一个处理程序.

Vuex mutations are essentially events: each mutation has a name and a handler.

import Vuex from 'vuex'

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    INCREMENT (state) {
      // mutate state
      state.count++
    }
  }
})

Actions:Actions 只是调度突变的函数.

Actions: Actions are just functions that dispatch mutations.

// the simplest action
function increment ({commit}) {
  commit('INCREMENT')
}

// a action with additional arguments
// with ES2015 argument destructuring
function incrementBy ({ dispatch }, amount) {
  dispatch('INCREMENT', amount)
}

以下是我对上述内容的解释:

Here is my explanation of the above:

  • 变异唯一的方法修改状态
  • mutation 不关心业务逻辑,只关心状态"
  • 动作是业务逻辑
  • action 一次可以提交 1个以上的mutation,它只实现业务逻辑,不关心数据变化(由mutation管理)
  • mutation is the only way to modify state
  • mutation doesn't care about business logic, it just cares about "state"
  • action is business logic
  • action can commit more than 1 mutation at a time, it just implements the business logic, it doesn't care about data changing (which manage by mutation)

这篇关于Vuex 动作与突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆