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 笔记 #9

Open
isNeilLin opened this issue Nov 2, 2017 · 0 comments
Open

Vuex 笔记 #9

isNeilLin opened this issue Nov 2, 2017 · 0 comments
Labels
框架&工具库 Vue和React等前端框架或工具库相关

Comments

@isNeilLin
Copy link
Owner

Vuex 笔记

Getter

store中的计算属性。getter接收state作为第一个参数,其他getter作为第二个参数。
getter会暴露为store.getters对象。

mapGetters辅助函数将store中的getter映射到局部计算属性

Mutation

mutation是更改store中状态的唯一方法。每个mutation都有一个接受字符串的事件类型(type)和一个回调函数。回调函数接受state作为第一个参数。第二个参数为commit提交的payload
要出发回调函数需要以相应的type调用store.commit方法。
可以在组件中使用this.$store.commit('xxx')提交mutation,或者使用mapMutations辅助函数将组件中的methods映射为store.commit调用。

mutation必须是同步类型

Action

Action类似与Mutation。不同之处在于:

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

Action函数接受一个与store实例具有相同方法和属性的context对象作为参数。因此可以调用context.commit提交一个mutation,或者通过context.statecontext.getters来获取stategetters

Action通过store.dispatch触发。Action同样支持载荷方式和对象方式进行分发

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})
// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用

Module

vuex可以将store分割成模块module。每个模块拥有自己的state,getter,mutation,action,甚至嵌套子模块。

模块内部的gettermutaion接收的第一个参数是模块的局部状态对象。对于模块内部的action,state通过contaxt.state对象暴露出来。根结点状态则为context.rootState。对于模块内部的getter,根结点状态会作为第三个参数暴露出来。

Plugins

vuex的store接受plugins选项。这个选项暴露出每次 mutation 的钩子。vuex插件就是一个函数,它接受store作为唯一参数

const myPlugin = store => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
  })
}

然后像这样使用:

const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})

在插件中不允许直接修改状态——类似于组件,只能通过提交 mutation 来触发变化。

@isNeilLin isNeilLin added the Vue label Nov 2, 2017
@isNeilLin isNeilLin added 框架&工具库 Vue和React等前端框架或工具库相关 and removed Vue labels Jun 18, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
框架&工具库 Vue和React等前端框架或工具库相关
Projects
None yet
Development

No branches or pull requests

1 participant