Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vuex #33

Open
shangguanhonglei opened this issue May 3, 2021 · 0 comments
Open

Vuex #33

shangguanhonglei opened this issue May 3, 2021 · 0 comments

Comments

@shangguanhonglei
Copy link
Owner

Vuex与全局变量的区别:

  • vuex的状态是响应式的
  • 不能直接改变store中的状态。改变状态的唯一途径就是显示的提交(commit) mutation

Vuex的几个核心概念

state

相当于 Vue 的 data 对象

  • Vuex使用单一状态树。每个应用仅仅包含一个store实例。
  • Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex))
  • 通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到
  • 放入state中的属性最好是公用的,如果是某个组件私有的,则不建议放入
mapState辅助函数
  • mapState 返回一个对象,可以使用展开运算符混合到computed中

Getter

相当于 Vue 的 computed 对象

Vuex允许在store中定义getter。

  • Getter接收state作为第一个参数
  • Getter会暴露 store.getters 对象
  • Getter也可以接收其他Getter作为第二个参数
  • 可以在组件中使用this.$store.getters.XXX
mapGetters 辅助函数

Mutation

  • 更改Vuex store中状态的唯一方式是 提交 mutation
  • 只能通过 store.commit(mutation)方法来调用mutation,而不能直接调用mutation handler
  • mutation 接收 state 作为第一个参数
  • commit 的一个参数是 type (即方法名,事件类型),第二个参数是载荷(payload, 即额外参数,大多数情况下是个对象)
  • 使用常量来代替mutation 的type(事件类型)
  • mutation必须是同步函数
提交载荷(Payload)

可以像 store.commit中传入额外参数, 即 mutation的载荷

store.commit('increment', 10)
increment (state, payload)

Action

  • action 类似于 mutation, 但区别如下:
  • mutation只处理同步事务
  • action提交的是 mutation,而不是直接变更状态。
  • action可以包含任意异步操作

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。但是 context对象并不是 store 实例本身

  • Action 通过 store.dispatch 方法触发 mutation
  • Store.dispatch 仍旧返回 promise
  • 一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant