如何将Vue中复用Vuex.store对象的定义改写为一个长尾词?

2026-04-01 14:402阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计4263个文字,预计阅读时间需要18分钟。

如何将Vue中复用Vuex.store对象的定义改写为一个长尾词?

目录 + 使用vuex.store对象定义

1.共用的store定义

2.组1 + 组2

Vuex中的store

1.Vuex是什么

2.Store

3.一个完整的Store结构

4.状态管理的几个核心概念

5.store与$store的区别

复用vuex.store对象

目录
  • 复用vuex.store对象的定义
    • 1. 共用的store定义
    • 2. 组件1
    • 3. 组件2
  • vuex中的store
    • 1. Vuex是什么
    • 2. Store
    • 3. 一个完整的Store结构
    • 4. 状态管理的几个核心概念
    • 5. store与$store的区别

复用vuex.store对象的定义

我有几个组件,都需要用到vuex.store,而且这几个组件结构极其类似,就在想,能不能复用store的对象定义?因为每个组件都定义一遍,繁琐,且没必要。

主要是用到克隆组件。具体代码如下:

1. 共用的store定义

/src/store/common.js

export default {   namespaced: true,   state: {     v: "hello store", // for test     items: [],   },   getters: {     v: (state) => state.v,     items: (state) => {       return state.items;     },   },   mutations: {     // 同步操作     setV(state, val) {       state.v = val;     },     setItems(state, val) {       state.items = val;     },   },   actions: {     keepItems: ({ commit }, val) => {       commit("setItems", val);     },   }, };

2. 组件1

/src/store/component1.js

import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component1;

3. 组件2

/src/store/component2.js

import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component2;

vuex中的store

1. Vuex是什么

在了解Store之前,我们先来看看Vuex是个什么东西。Vuex本质上就是一个Vue.js的插件,是用于对复杂应用进行状态管理用的,打印Vuex以后输出:

如何将Vue中复用Vuex.store对象的定义改写为一个长尾词?

{   ​ Store: function Store(){},   ​ mapActions: function(){}, // 对应Actions的结果集   ​ mapGetters: function(){}, // 对应Getters的结果集   ​ mapMutations: function(){}, // 对应Mutations的结果集   ​ mapState: function(){}, // 对应State的结果集   ​ install: function install(){},   ​ installed: true   }

Vuex和单纯的全局对象有以下两点不同:

  • Vuex的状态存储是响应式的。当Vue 组件从 Store 中读取状态的时候,若 Store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  • 不能直接改变 Store 中的状态。改变Store 中的状态的唯一途径就是显式地提交 mutation。

2. Store

每一个Vuex应用的核心就是Store(仓库),我们可以说Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变Store中的状态。想要改变Store中的状态,只有一个办法,显式地提交mutation。

3. 一个完整的Store结构

const store = new Vuex.Store({   state: {     // 存放状态   },   getters: {     // state的计算属性   },   mutations: {     // 更改state中状态的逻辑,同步操作   },   actions: {     // 提交mutation,异步操作   },   // 如果将store分成一个个的模块的话,则需要用到modules。    //然后在每一个module中写state, getters, mutations, actions等。   modules: {     a: moduleA,     b: moduleB,     // ...   } });

4. 状态管理的几个核心概念

1. state

state是状态数据,可以通过this.$store.state来直接获取状态,也可以利用vuex提供的mapState辅助函数将state映射到计算属性(computed)中去。用data接收的值不能及时响应更新,用computed就可以:

export default {   data () {     return {       dataCount: this.$store.state.count //用data接收     }   },   computed:{     count(){       return this.$store.state.count //用computed接收     }   } }

mapState 辅助函数:

mapState是state的语法糖,当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex'   export default {   // ...   computed: mapState({     // 箭头函数可使代码更简练     count: state => state.count,       // 传字符串参数 'count' 等同于 `state => state.count`     countAlias: 'count',       // 为了能够使用 `this` 获取局部状态,必须使用常规函数     countPlusLocalState (state) {       return state.count + this.localCount     }   }) }

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([   // 映射 this.count 为 store.state.count   'count' ])

2. getter

getters本质上是用来对状态进行加工处理。Getters与State的关系,就像Vue.js的computed与data的关系。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。可以通过this.$store.getters.valueName对派生出来的状态进行访问。或者直接使用辅助函数mapGetters将其映射到本地计算属性中去。

mapGetters 辅助函数:

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

import { mapGetters } from 'vuex' export default {   // ...   computed: {   // 使用对象展开运算符将 getter 混入 computed 对象中     ...mapGetters([       'doneTodosCount',       'anotherGetter',       // ...     ])   } }

mapGetters实际上是一个方法Vuex对象上的一个方法,这从本文开头打印的那个Vuex对象的内容可以看出来。…这个符号是ES2015的一个新的语法糖,即将mapGetters处理后的内容展开后填入。

如果你想将一个 getter 属性另取一个名字,使用对象形式:

mapGetters({   // 映射 `this.doneCount` 为 `store.getters.doneTodosCount`   doneCount: 'doneTodosCount' })

3. mutation

mutations的中文意思是“变化”,利用它可以更改状态。事实上,更改 Vuex 的 store 中的状态的唯一方法就是提交 (commit)mutation。不过,mutation触发状态改变的方式有一点特别,所谓commit一个mutation,实际是像触发一个事件一样,传入一个mutation的类型以及携带一些数据(称作payload,载荷)。

mutations: {   //放置mutations方法     increment(state, payload) {         //在这里改变state中的数据         state.count = payload.number;     } },

那commit一个mutation在代码层面怎么表示呢?

this.$store.commit('increment', {   amount: 10 }) //或者这样 this.$store.commit({   type: 'increment',   amount: 10 })

除了这种使用 this.$store.commit('xxx') 提交 mutation的方式之外,还有一种方式,即使用 mapMutations 辅助函数将组件中的 methods 映射为 this.$store.commit。例如:

import { mapMutations } from 'vuex'   export default {   // ...   methods: {     ...mapMutations([       'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`         // `mapMutations` 也支持载荷:       'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`     ]),     ...mapMutations({       add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`     })   } }

经过这样的映射之后,就可以通过调用方法的方式来触发其对应的(所映射到的)mutation commit了,比如,上例中调用add()方法,就相当于执行了this.$store.commit('increment')了。

考虑到触发的mutation的type必须与mutations里声明的mutation名称一致,比较好的方式是把这些mutation都集中到一个文件(如mutation-types)中以常量的形式定义,在其它地方再将这个文件引入,便于管理。而且这样做还有一个好处,就是整个应用中一共有哪些mutation type可以一目了然。就像下面这样:

// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION'   // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types'   const store = new Vuex.Store({   state: { ... },   mutations: {     // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名     [SOME_MUTATION] (state) {       // mutate state     }   } })

4. action

action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作:

const store = new Vuex.Store({   state: {     count: 0   },   mutations: {     increment (state) {       state.count++     }   },   actions: {     increment (context) {       context.commit('increment')     }   } })

或者用ES2015的参数解构,可以简写成:

actions: {     increment ({commit}) {           commit('increment')     } }

和mutation类似,我们像上面这样生命action的处理函数。它接收的第一个参数是一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

不过,mutation处理函数中所做的事情是改变state,而action处理函数中所做的事情则是commit mutation。

怎么触发action呢?按照Vuex的叫法,这叫分发(dispatch),我们反正知道它实际上是触发的意思就行了。具体的触发方法是this.$store.dispatch(actionType, payload)。所传的两个参数一个是要触发的action的类型,一个是所携带的数据(payload),类似于上文所讲的commit mutation时所传的那两个参数。具体如下:

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

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

还有一种方法是使用 mapActions 辅助函数将组件的 methods 映射为 this.$store.dispatch 调用。如下:

import { mapActions } from 'vuex'   export default {   // ...   methods: {     ...mapActions([       'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`         // `mapActions` 也支持载荷:       'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`     ]),     ...mapActions({       add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`     })   } }

另外,还需要知道, this.$store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 this.$store.dispatch 仍旧返回 Promise。

再来看一些组合性的异步操作:

actions: {   actionA ({ commit }) {     return new Promise((resolve, reject) => {       setTimeout(() => {         commit('someMutation')         resolve()       }, 1000)     })   } }

现在你可以:

$this.store.dispatch('actionA').then(() => {   // ... })

在另外一个 action 中也可以:

actions: {   // ...   actionB ({ dispatch, commit }) {     return dispatch('actionA').then(() => {       commit('someOtherMutation')     })   } }

最后,如果我们利用 async / await 这个 JavaScript 即将到来的新特性,我们可以像这样组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise actions: {   async actionA ({ commit }) {     commit('gotData', await getData())   },   async actionB ({ dispatch, commit }) {     await dispatch('actionA') // 等待 actionA 完成     commit('gotOtherData', await getOtherData())   } }

接着来看一个更加实际的购物车示例,涉及到调用异步 API 和分发多重 mutation:

actions: {   checkout ({ commit, state }, products) {     // 把当前购物车的物品备份起来     const savedCartItems = [...state.cart.added]     // 发出结账请求,然后乐观地清空购物车     commit(types.CHECKOUT_REQUEST)     // 购物 API 接受一个成功回调和一个失败回调     shop.buyProducts(       products,       // 成功操作       () => commit(types.CHECKOUT_SUCCESS),       // 失败操作       () => commit(types.CHECKOUT_FAILURE, savedCartItems)     )   } }

5. module

module是对于store的一种切割。由于Vuex使用的是单一状态树,这样整个应用的所有状态都会集中到一个比较大的对象上面,那么,当应用变得非常复杂时,store 对象就很可能变得相当臃肿!它解决了当state中很臃肿的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。就像下面这样:

const moduleA = {   state: { ... },   mutations: { ... },   actions: { ... },   getters: { ... } }   const moduleB = {   state: { ... },   mutations: { ... },   actions: { ... } }   const store = new Vuex.Store({   modules: {     a: moduleA,     b: moduleB   } })   store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态

模块的局部状态

对于每个模块内部的 mutation 和 getter,接收的第一个参数就是模块的局部状态对象。

const moduleA = {   state: { count: 0 },   mutations: {     increment (state) {       // 这里的 `state` 对象是模块的局部状态       state.count++     }   },     getters: {     doubleCount (state) {       return state.count * 2     }   } }

同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

const moduleA = {   // ...   actions: {     incrementIfOddOnRootSum ({ state, commit, rootState }) {       if ((state.count + rootState.count) % 2 === 1) {         commit('increment')       }     }   } }

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {   // ...   getters: {     sumWithRootCount (state, getters, rootState) {       return state.count + rootState.count     }   } }

命名空间

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为命名空间模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

例如:

const store = new Vuex.Store({   modules: {     account: {       namespaced: true,         // 模块内容(module assets)       state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响       getters: {         isAdmin () { ... } // -> getters['account/isAdmin']       },       actions: {         login () { ... } // -> dispatch('account/login')       },       mutations: {         login () { ... } // -> commit('account/login')       },         // 嵌套模块       modules: {         // 继承父模块的命名空间         myPage: {           state: { ... },           getters: {             profile () { ... } // -> getters['account/profile']           }         },           // 进一步嵌套命名空间         posts: {           namespaced: true,             state: { ... },           getters: {             popular () { ... } // -> getters['account/posts/popular']           }         }       }     }   } })

启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。

在命名空间模块内访问全局内容(Global Assets)

如果你希望使用全局 state 和 getter,rootState 和 rootGetter 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。

若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit即可。

modules: {   foo: {     namespaced: true,       getters: {       // 在这个模块的 getter 中,`getters` 被局部化了       // 你可以使用 getter 的第四个参数来调用 `rootGetters`       someGetter (state, getters, rootState, rootGetters) {         getters.someOtherGetter // -> 'foo/someOtherGetter'         rootGetters.someOtherGetter // -> 'someOtherGetter'       },       someOtherGetter: state => { ... }     },       actions: {       // 在这个模块中, dispatch 和 commit 也被局部化了       // 他们可以接受 `root` 属性以访问根 dispatch 或 commit       someAction ({ dispatch, commit, getters, rootGetters }) {         getters.someGetter // -> 'foo/someGetter'         rootGetters.someGetter // -> 'someGetter'           dispatch('someOtherAction') // -> 'foo/someOtherAction'         dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'           commit('someMutation') // -> 'foo/someMutation'         commit('someMutation', null, { root: true }) // -> 'someMutation'       },       someOtherAction (ctx, payload) { ... }     }   } }

带命名空间的绑定函数

当使用 mapState, mapGetters, mapActions 和 mapMutations 这些函数来绑定命名空间模块时,写起来可能比较繁琐:

computed: {   ...mapState({     a: state => state.some.nested.module.a,     b: state => state.some.nested.module.b   }) }, methods: {   ...mapActions([     'some/nested/module/foo',     'some/nested/module/bar'   ]) }

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:

computed: {   ...mapState('some/nested/module', {     a: state => state.a,     b: state => state.b   }) }, methods: {   ...mapActions('some/nested/module', [     'foo',     'bar'   ]) }

而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

import { createNamespacedHelpers } from 'vuex'   const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')   export default {   computed: {     // 在 `some/nested/module` 中查找     ...mapState({       a: state => state.a,       b: state => state.b     })   },   methods: {     // 在 `some/nested/module` 中查找     ...mapActions([       'foo',       'bar'     ])   } }

给插件开发者的注意事项

如果你开发的插件(Plugin)提供了模块并允许用户将其添加到 Vuex store,可能需要考虑模块的空间名称问题。对于这种情况,你可以通过插件的参数对象来允许用户指定空间名称:

// 通过插件的参数对象得到空间名称 // 然后返回 Vuex 插件函数 export function createPlugin (options = {}) {   return function (store) {     // 把空间名字添加到插件模块的类型(type)中去     const namespace = options.namespace || ''     store.dispatch(namespace + 'pluginAction')   } }

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

// 注册模块 `myModule` store.registerModule('myModule', {   // ... }) // 注册嵌套模块 `nested/myModule` store.registerModule(['nested', 'myModule'], {   // ... })

之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。

模块动态注册功能使得其他 Vue 插件可以通过在 store 中附加新模块的方式来使用 Vuex 管理状态。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的路由状态管理。

你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。

模块重用

有时我们可能需要创建一个模块的多个实例,例如:

(1)创建多个 store,他们公用同一个模块

(2)在一个 store 中多次注册同一个模块

如果我们使用一个纯对象来声明模块的状态,那么这个状态对象会通过引用被共享,导致状态对象被修改时 store 或模块间数据互相污染的问题。

实际上这和 Vue 组件内的 data 是同样的问题。因此解决办法也是相同的——使用一个函数来声明模块状态(仅 2.3.0+ 支持):

const MyReusableModule = {   state () {     return {       foo: 'bar'     }   },   // mutation, action 和 getter 等等... }

5. store与$store的区别

$store 是挂载在 Vue 实例上的(即Vue.prototype),组件也是一个Vue实例,在组件中可使用 this 访问原型上的属性。template 中可直接通过 {{ $store.state.userName }} 访问,等价于 script 中的 this.$store.state.userName。

至于 {{ store.state.userName }},script 中的 data 需声明过 store 才可访问。

总之,有以下要注意的:

(1)在功能上:

  • state保存的是数据
  • getters是对state进行二次加工
  • action的处理函数的功能最终是commit mutation
  • mutation处理函数的功能最终是改变state

(2)在流程上:

vue component—-dispatch—->actions—-commit—->mutations—-mutate—->state—-render—->vue component。从而形成闭环。

(3)辅助方法的映射上:

mapGetters、mapState 都是用在computed声明里面;

mapActions、mapMutations则都是用在methods声明里面。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:定义目录

本文共计4263个文字,预计阅读时间需要18分钟。

如何将Vue中复用Vuex.store对象的定义改写为一个长尾词?

目录 + 使用vuex.store对象定义

1.共用的store定义

2.组1 + 组2

Vuex中的store

1.Vuex是什么

2.Store

3.一个完整的Store结构

4.状态管理的几个核心概念

5.store与$store的区别

复用vuex.store对象

目录
  • 复用vuex.store对象的定义
    • 1. 共用的store定义
    • 2. 组件1
    • 3. 组件2
  • vuex中的store
    • 1. Vuex是什么
    • 2. Store
    • 3. 一个完整的Store结构
    • 4. 状态管理的几个核心概念
    • 5. store与$store的区别

复用vuex.store对象的定义

我有几个组件,都需要用到vuex.store,而且这几个组件结构极其类似,就在想,能不能复用store的对象定义?因为每个组件都定义一遍,繁琐,且没必要。

主要是用到克隆组件。具体代码如下:

1. 共用的store定义

/src/store/common.js

export default {   namespaced: true,   state: {     v: "hello store", // for test     items: [],   },   getters: {     v: (state) => state.v,     items: (state) => {       return state.items;     },   },   mutations: {     // 同步操作     setV(state, val) {       state.v = val;     },     setItems(state, val) {       state.items = val;     },   },   actions: {     keepItems: ({ commit }, val) => {       commit("setItems", val);     },   }, };

2. 组件1

/src/store/component1.js

import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component1;

3. 组件2

/src/store/component2.js

import cloneDeep from "lodash/cloneDeep"; import common from "./common"; const category = cloneDeep(common); export default component2;

vuex中的store

1. Vuex是什么

在了解Store之前,我们先来看看Vuex是个什么东西。Vuex本质上就是一个Vue.js的插件,是用于对复杂应用进行状态管理用的,打印Vuex以后输出:

如何将Vue中复用Vuex.store对象的定义改写为一个长尾词?

{   ​ Store: function Store(){},   ​ mapActions: function(){}, // 对应Actions的结果集   ​ mapGetters: function(){}, // 对应Getters的结果集   ​ mapMutations: function(){}, // 对应Mutations的结果集   ​ mapState: function(){}, // 对应State的结果集   ​ install: function install(){},   ​ installed: true   }

Vuex和单纯的全局对象有以下两点不同:

  • Vuex的状态存储是响应式的。当Vue 组件从 Store 中读取状态的时候,若 Store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  • 不能直接改变 Store 中的状态。改变Store 中的状态的唯一途径就是显式地提交 mutation。

2. Store

每一个Vuex应用的核心就是Store(仓库),我们可以说Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变Store中的状态。想要改变Store中的状态,只有一个办法,显式地提交mutation。

3. 一个完整的Store结构

const store = new Vuex.Store({   state: {     // 存放状态   },   getters: {     // state的计算属性   },   mutations: {     // 更改state中状态的逻辑,同步操作   },   actions: {     // 提交mutation,异步操作   },   // 如果将store分成一个个的模块的话,则需要用到modules。    //然后在每一个module中写state, getters, mutations, actions等。   modules: {     a: moduleA,     b: moduleB,     // ...   } });

4. 状态管理的几个核心概念

1. state

state是状态数据,可以通过this.$store.state来直接获取状态,也可以利用vuex提供的mapState辅助函数将state映射到计算属性(computed)中去。用data接收的值不能及时响应更新,用computed就可以:

export default {   data () {     return {       dataCount: this.$store.state.count //用data接收     }   },   computed:{     count(){       return this.$store.state.count //用computed接收     }   } }

mapState 辅助函数:

mapState是state的语法糖,当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex'   export default {   // ...   computed: mapState({     // 箭头函数可使代码更简练     count: state => state.count,       // 传字符串参数 'count' 等同于 `state => state.count`     countAlias: 'count',       // 为了能够使用 `this` 获取局部状态,必须使用常规函数     countPlusLocalState (state) {       return state.count + this.localCount     }   }) }

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。

computed: mapState([   // 映射 this.count 为 store.state.count   'count' ])

2. getter

getters本质上是用来对状态进行加工处理。Getters与State的关系,就像Vue.js的computed与data的关系。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。可以通过this.$store.getters.valueName对派生出来的状态进行访问。或者直接使用辅助函数mapGetters将其映射到本地计算属性中去。

mapGetters 辅助函数:

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

import { mapGetters } from 'vuex' export default {   // ...   computed: {   // 使用对象展开运算符将 getter 混入 computed 对象中     ...mapGetters([       'doneTodosCount',       'anotherGetter',       // ...     ])   } }

mapGetters实际上是一个方法Vuex对象上的一个方法,这从本文开头打印的那个Vuex对象的内容可以看出来。…这个符号是ES2015的一个新的语法糖,即将mapGetters处理后的内容展开后填入。

如果你想将一个 getter 属性另取一个名字,使用对象形式:

mapGetters({   // 映射 `this.doneCount` 为 `store.getters.doneTodosCount`   doneCount: 'doneTodosCount' })

3. mutation

mutations的中文意思是“变化”,利用它可以更改状态。事实上,更改 Vuex 的 store 中的状态的唯一方法就是提交 (commit)mutation。不过,mutation触发状态改变的方式有一点特别,所谓commit一个mutation,实际是像触发一个事件一样,传入一个mutation的类型以及携带一些数据(称作payload,载荷)。

mutations: {   //放置mutations方法     increment(state, payload) {         //在这里改变state中的数据         state.count = payload.number;     } },

那commit一个mutation在代码层面怎么表示呢?

this.$store.commit('increment', {   amount: 10 }) //或者这样 this.$store.commit({   type: 'increment',   amount: 10 })

除了这种使用 this.$store.commit('xxx') 提交 mutation的方式之外,还有一种方式,即使用 mapMutations 辅助函数将组件中的 methods 映射为 this.$store.commit。例如:

import { mapMutations } from 'vuex'   export default {   // ...   methods: {     ...mapMutations([       'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`         // `mapMutations` 也支持载荷:       'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`     ]),     ...mapMutations({       add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`     })   } }

经过这样的映射之后,就可以通过调用方法的方式来触发其对应的(所映射到的)mutation commit了,比如,上例中调用add()方法,就相当于执行了this.$store.commit('increment')了。

考虑到触发的mutation的type必须与mutations里声明的mutation名称一致,比较好的方式是把这些mutation都集中到一个文件(如mutation-types)中以常量的形式定义,在其它地方再将这个文件引入,便于管理。而且这样做还有一个好处,就是整个应用中一共有哪些mutation type可以一目了然。就像下面这样:

// mutation-types.js export const SOME_MUTATION = 'SOME_MUTATION'   // store.js import Vuex from 'vuex' import { SOME_MUTATION } from './mutation-types'   const store = new Vuex.Store({   state: { ... },   mutations: {     // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名     [SOME_MUTATION] (state) {       // mutate state     }   } })

4. action

action可以提交mutation,在action中可以执行store.commit,而且action中可以有任何的异步操作:

const store = new Vuex.Store({   state: {     count: 0   },   mutations: {     increment (state) {       state.count++     }   },   actions: {     increment (context) {       context.commit('increment')     }   } })

或者用ES2015的参数解构,可以简写成:

actions: {     increment ({commit}) {           commit('increment')     } }

和mutation类似,我们像上面这样生命action的处理函数。它接收的第一个参数是一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

不过,mutation处理函数中所做的事情是改变state,而action处理函数中所做的事情则是commit mutation。

怎么触发action呢?按照Vuex的叫法,这叫分发(dispatch),我们反正知道它实际上是触发的意思就行了。具体的触发方法是this.$store.dispatch(actionType, payload)。所传的两个参数一个是要触发的action的类型,一个是所携带的数据(payload),类似于上文所讲的commit mutation时所传的那两个参数。具体如下:

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

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

还有一种方法是使用 mapActions 辅助函数将组件的 methods 映射为 this.$store.dispatch 调用。如下:

import { mapActions } from 'vuex'   export default {   // ...   methods: {     ...mapActions([       'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`         // `mapActions` 也支持载荷:       'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`     ]),     ...mapActions({       add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`     })   } }

另外,还需要知道, this.$store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 this.$store.dispatch 仍旧返回 Promise。

再来看一些组合性的异步操作:

actions: {   actionA ({ commit }) {     return new Promise((resolve, reject) => {       setTimeout(() => {         commit('someMutation')         resolve()       }, 1000)     })   } }

现在你可以:

$this.store.dispatch('actionA').then(() => {   // ... })

在另外一个 action 中也可以:

actions: {   // ...   actionB ({ dispatch, commit }) {     return dispatch('actionA').then(() => {       commit('someOtherMutation')     })   } }

最后,如果我们利用 async / await 这个 JavaScript 即将到来的新特性,我们可以像这样组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise actions: {   async actionA ({ commit }) {     commit('gotData', await getData())   },   async actionB ({ dispatch, commit }) {     await dispatch('actionA') // 等待 actionA 完成     commit('gotOtherData', await getOtherData())   } }

接着来看一个更加实际的购物车示例,涉及到调用异步 API 和分发多重 mutation:

actions: {   checkout ({ commit, state }, products) {     // 把当前购物车的物品备份起来     const savedCartItems = [...state.cart.added]     // 发出结账请求,然后乐观地清空购物车     commit(types.CHECKOUT_REQUEST)     // 购物 API 接受一个成功回调和一个失败回调     shop.buyProducts(       products,       // 成功操作       () => commit(types.CHECKOUT_SUCCESS),       // 失败操作       () => commit(types.CHECKOUT_FAILURE, savedCartItems)     )   } }

5. module

module是对于store的一种切割。由于Vuex使用的是单一状态树,这样整个应用的所有状态都会集中到一个比较大的对象上面,那么,当应用变得非常复杂时,store 对象就很可能变得相当臃肿!它解决了当state中很臃肿的时候,module可以将store分割成模块,每个模块中拥有自己的state、mutation、action和getter。就像下面这样:

const moduleA = {   state: { ... },   mutations: { ... },   actions: { ... },   getters: { ... } }   const moduleB = {   state: { ... },   mutations: { ... },   actions: { ... } }   const store = new Vuex.Store({   modules: {     a: moduleA,     b: moduleB   } })   store.state.a // -> moduleA 的状态 store.state.b // -> moduleB 的状态

模块的局部状态

对于每个模块内部的 mutation 和 getter,接收的第一个参数就是模块的局部状态对象。

const moduleA = {   state: { count: 0 },   mutations: {     increment (state) {       // 这里的 `state` 对象是模块的局部状态       state.count++     }   },     getters: {     doubleCount (state) {       return state.count * 2     }   } }

同样,对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState:

const moduleA = {   // ...   actions: {     incrementIfOddOnRootSum ({ state, commit, rootState }) {       if ((state.count + rootState.count) % 2 === 1) {         commit('increment')       }     }   } }

对于模块内部的 getter,根节点状态会作为第三个参数暴露出来:

const moduleA = {   // ...   getters: {     sumWithRootCount (state, getters, rootState) {       return state.count + rootState.count     }   } }

命名空间

默认情况下,模块内部的 action、mutation 和 getter 是注册在全局命名空间的——这样使得多个模块能够对同一 mutation 或 action 作出响应。

如果希望你的模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为命名空间模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

例如:

const store = new Vuex.Store({   modules: {     account: {       namespaced: true,         // 模块内容(module assets)       state: { ... }, // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响       getters: {         isAdmin () { ... } // -> getters['account/isAdmin']       },       actions: {         login () { ... } // -> dispatch('account/login')       },       mutations: {         login () { ... } // -> commit('account/login')       },         // 嵌套模块       modules: {         // 继承父模块的命名空间         myPage: {           state: { ... },           getters: {             profile () { ... } // -> getters['account/profile']           }         },           // 进一步嵌套命名空间         posts: {           namespaced: true,             state: { ... },           getters: {             popular () { ... } // -> getters['account/posts/popular']           }         }       }     }   } })

启用了命名空间的 getter 和 action 会收到局部化的 getter,dispatch 和 commit。

在命名空间模块内访问全局内容(Global Assets)

如果你希望使用全局 state 和 getter,rootState 和 rootGetter 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。

若需要在全局命名空间内分发 action 或提交 mutation,将 { root: true } 作为第三参数传给 dispatch 或 commit即可。

modules: {   foo: {     namespaced: true,       getters: {       // 在这个模块的 getter 中,`getters` 被局部化了       // 你可以使用 getter 的第四个参数来调用 `rootGetters`       someGetter (state, getters, rootState, rootGetters) {         getters.someOtherGetter // -> 'foo/someOtherGetter'         rootGetters.someOtherGetter // -> 'someOtherGetter'       },       someOtherGetter: state => { ... }     },       actions: {       // 在这个模块中, dispatch 和 commit 也被局部化了       // 他们可以接受 `root` 属性以访问根 dispatch 或 commit       someAction ({ dispatch, commit, getters, rootGetters }) {         getters.someGetter // -> 'foo/someGetter'         rootGetters.someGetter // -> 'someGetter'           dispatch('someOtherAction') // -> 'foo/someOtherAction'         dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'           commit('someMutation') // -> 'foo/someMutation'         commit('someMutation', null, { root: true }) // -> 'someMutation'       },       someOtherAction (ctx, payload) { ... }     }   } }

带命名空间的绑定函数

当使用 mapState, mapGetters, mapActions 和 mapMutations 这些函数来绑定命名空间模块时,写起来可能比较繁琐:

computed: {   ...mapState({     a: state => state.some.nested.module.a,     b: state => state.some.nested.module.b   }) }, methods: {   ...mapActions([     'some/nested/module/foo',     'some/nested/module/bar'   ]) }

对于这种情况,你可以将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。于是上面的例子可以简化为:

computed: {   ...mapState('some/nested/module', {     a: state => state.a,     b: state => state.b   }) }, methods: {   ...mapActions('some/nested/module', [     'foo',     'bar'   ]) }

而且,你可以通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数:

import { createNamespacedHelpers } from 'vuex'   const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')   export default {   computed: {     // 在 `some/nested/module` 中查找     ...mapState({       a: state => state.a,       b: state => state.b     })   },   methods: {     // 在 `some/nested/module` 中查找     ...mapActions([       'foo',       'bar'     ])   } }

给插件开发者的注意事项

如果你开发的插件(Plugin)提供了模块并允许用户将其添加到 Vuex store,可能需要考虑模块的空间名称问题。对于这种情况,你可以通过插件的参数对象来允许用户指定空间名称:

// 通过插件的参数对象得到空间名称 // 然后返回 Vuex 插件函数 export function createPlugin (options = {}) {   return function (store) {     // 把空间名字添加到插件模块的类型(type)中去     const namespace = options.namespace || ''     store.dispatch(namespace + 'pluginAction')   } }

模块动态注册

在 store 创建之后,你可以使用 store.registerModule 方法注册模块:

// 注册模块 `myModule` store.registerModule('myModule', {   // ... }) // 注册嵌套模块 `nested/myModule` store.registerModule(['nested', 'myModule'], {   // ... })

之后就可以通过 store.state.myModule 和 store.state.nested.myModule 访问模块的状态。

模块动态注册功能使得其他 Vue 插件可以通过在 store 中附加新模块的方式来使用 Vuex 管理状态。例如,vuex-router-sync 插件就是通过动态注册模块将 vue-router 和 vuex 结合在一起,实现应用的路由状态管理。

你也可以使用 store.unregisterModule(moduleName) 来动态卸载模块。注意,你不能使用此方法卸载静态模块(即创建 store 时声明的模块)。

模块重用

有时我们可能需要创建一个模块的多个实例,例如:

(1)创建多个 store,他们公用同一个模块

(2)在一个 store 中多次注册同一个模块

如果我们使用一个纯对象来声明模块的状态,那么这个状态对象会通过引用被共享,导致状态对象被修改时 store 或模块间数据互相污染的问题。

实际上这和 Vue 组件内的 data 是同样的问题。因此解决办法也是相同的——使用一个函数来声明模块状态(仅 2.3.0+ 支持):

const MyReusableModule = {   state () {     return {       foo: 'bar'     }   },   // mutation, action 和 getter 等等... }

5. store与$store的区别

$store 是挂载在 Vue 实例上的(即Vue.prototype),组件也是一个Vue实例,在组件中可使用 this 访问原型上的属性。template 中可直接通过 {{ $store.state.userName }} 访问,等价于 script 中的 this.$store.state.userName。

至于 {{ store.state.userName }},script 中的 data 需声明过 store 才可访问。

总之,有以下要注意的:

(1)在功能上:

  • state保存的是数据
  • getters是对state进行二次加工
  • action的处理函数的功能最终是commit mutation
  • mutation处理函数的功能最终是改变state

(2)在流程上:

vue component—-dispatch—->actions—-commit—->mutations—-mutate—->state—-render—->vue component。从而形成闭环。

(3)辅助方法的映射上:

mapGetters、mapState 都是用在computed声明里面;

mapActions、mapMutations则都是用在methods声明里面。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持易盾网络。

标签:定义目录