Fe-interview: [vue] vuex的action和mutation的特性是什么?有什么区别?

Created on 20 Jun 2019  ·  4Comments  ·  Source: haizlin/fe-interview

[vue] vuex的action和mutation的特性是什么?有什么区别?

vue

Most helpful comment

Action

  • 一些对 State 的异步操作可放在 Action 中,并通过在 Action 中 commit Mutation 变更状态
  • Action 可通过 store.dispatch() 方法触发,或者通过 mapActions 辅助函数将 vue 组件的 methods 映射成 store.dispatch() 调用

Mutation

  • 在 vuex 的严格模式下,Mutaion 是 vuex 中改变 State 的唯一途径
  • Mutation 中只能是同步操作
  • 通过 store.commit() 调用 Mutation

All 4 comments

action: 负责与外界交互, 比如请求数据(好像一般都是)
mutation: 负责: 内部state变更

一个对外, 一个对内

action: 通过执行 commit()来触发mutation的调用, 间接更新state ,
组件中通过$store.dispatch('action名称') 触发action,
可以包含异步代码(定时器, ajax)
mutation是一个对象 包含多个直接更新state的方法(回调函数) ,只能包含同步的代码, 不能写异步代码

Action

  • 一些对 State 的异步操作可放在 Action 中,并通过在 Action 中 commit Mutation 变更状态
  • Action 可通过 store.dispatch() 方法触发,或者通过 mapActions 辅助函数将 vue 组件的 methods 映射成 store.dispatch() 调用

Mutation

  • 在 vuex 的严格模式下,Mutaion 是 vuex 中改变 State 的唯一途径
  • Mutation 中只能是同步操作
  • 通过 store.commit() 调用 Mutation

Action
1.可以包含任意异步操作
2.它提交的是mutation,而不是直接变更状态

Mutation
1.唯一一个可以修改state的途径
2.必须是同步函数

Was this page helpful?
0 / 5 - 0 ratings