vuex梳理

### store

1. Vue 组件中获得 Vuex 状态

```js

//方式一 全局引入单例类

// 创建一个 Counter 组件

const Counter = {

  template: `<div>{{ count }}</div>`,

  computed: {

    count () {

      return store.state.count 

    }

  }

}

// Vue.use(Vuex)

const app = new Vue({

  el: '#app',

  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件

  store,

  components: { Counter },

  template: `

    <div class="app">

      <counter></counter>

    </div>

  `

})

组件中实现:

const Counter = {

  template: `<div>{{ count }}</div>`,

  computed: {

    count () {

      return this.$store.state.count

    }

  }

}

```

2. mapState 辅助函数

> 为了解决声明N多计算属性冗余

```js

// 在单独构建的版本中辅助函数为 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 传一个字符串数组。

```js

computed: mapState([

  // 映射 this.count 为 store.state.count

  'count'

])

```

3.对象展开运算符

> 我们如何将它与局部计算属性混合使用呢?通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。

```js

// 通过对象展开运算符简化写法

computed: {

  localComputed () { /* ... */ },

  // 使用对象展开运算符将此对象混入到外部对象中

  ...mapState({

    // ...

  })

}

```

### Getter

1. getter引入

> 有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:

```js

computed: {

  doneTodosCount () {

    return this.$store.state.todos.filter(todo => todo.done).length

  }

}

```

>如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它——无论哪种方式都不是很理想。

>Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

```js

const store = new Vuex.Store({

  state: {

    todos: [

      { id: 1, text: '...', done: true },

      { id: 2, text: '...', done: false }

    ]

  },

  getters: {

    doneTodos: state => {

      return state.todos.filter(todo => todo.done)

    }

  }

})

```

2. 通过属性访问

注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。

> Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:

```js

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

```

>Getter 也可以接受其他 getter 作为第二个参数:

```js

getters: {

  // ...

  doneTodosCount: (state, getters) => {

    return getters.doneTodos.length

  }

}

// 获取

store.getters.doneTodosCount // -> 1

// 组件中使用

computed: {

  doneTodosCount () {

    return this.$store.getters.doneTodosCount

  }

}

```

3. 通过方法访问

注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。

>你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

```js

getters: {

  // ...

  getTodoById: (state) => (id) => {

    return state.todos.find(todo => todo.id === id)

  }

}

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

```

4. mapGetters 辅助函数

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

```js

import { mapGetters } from 'vuex'

export default {

  // ...

  computed: {

  // 使用对象展开运算符将 getter 混入 computed 对象中

    ...mapGetters([

      'doneTodosCount',

      'anotherGetter',

      // ...

    ])

  }

}

```

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

```js

mapGetters({

  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`

  doneCount: 'doneTodosCount'

})

```

### Mutation

1. 事件定义

> 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

```js

const store = new Vuex.Store({

  state: {

    count: 1

  },

  mutations: {

    increment (state) {

      // 变更状态

      state.count++

    }

  }

})

// 调用

store.commit('increment')

```

2. 提交载荷(Payload)(传递参数)

```js

mutations: {

  increment (state, n) {

    state.count += n

  }

}

store.commit('increment', 10)

```

3.对象风格的提交方式

>当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变:

```js

store.commit({

  type: 'increment',

  amount: 10

})

// store 中

mutations: {

  increment (state, payload) {

    state.count += payload.amount

  }

}

```

4. Mutation 需遵守 Vue 的响应规则

>

既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:

- 最好提前在你的 store 中初始化好所有所需属性。

- 当需要在对象上添加新属性时,你应该

- [x]  使用 Vue.set(obj, 'newProp', 123), 或者

- [x]  以新对象替换老对象

```js

state.obj = { ...state.obj, newProp: 123 }

```

5.使用常量替代 Mutation 事件类型

```js

// mutation-types.js

export const SOME_MUTATION = 'SOME_MUTATION'

```

```js

// 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

    }

  }

})

```

6.  Mutation 必须是同步函数

>  一条重要的原则就是要记住 mutation 必须是同步函数

```js

mutations: {

  someMutation (state) {

    api.callAsyncMethod(() => {

      state.count++

    })

  }

}

```

7.  在组件中提交 Mutation

>你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

```js

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')`

    })

  }

}

```

### Action

1.

Action 类似于 mutation,不同在于:

- Action 提交的是 mutation,而不是直接变更状态。

- Action 可以包含任意异步操作

- Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象

```js

const store = new Vuex.Store({

  state: {

    count: 0

  },

  mutations: {

    increment (state) {

      state.count++

    }

  },

  actions: {

    increment (context) {

      context.commit('increment')

    }

  }

})

// 通过解构简化

actions: {

  increment ({ commit }) {

    commit('increment')

  }

}

```

2. 分发 Action

```js

store.dispatch('increment')

```

异步操作

```js

actions: {

  incrementAsync ({ commit }) {

    setTimeout(() => {

      commit('increment')

    }, 1000)

  }

}

// 以载荷形式分发

store.dispatch('incrementAsync', {

  amount: 10

})

// 以对象形式分发

store.dispatch({

  type: 'incrementAsync',

  amount: 10

})

```

3.实际的购物车示例,涉及到调用异步 API 和分发多重 mutation:

```js

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)

    )

  }

}

```

4.在组件中分发 Action

>

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store

```js

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')`

    })

  }

}

```

5. 组合 Action

>store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise

```js

actions: {

  actionA ({ commit }) {

    return new Promise((resolve, reject) => {

      setTimeout(() => {

        commit('someMutation')

        resolve()

      }, 1000)

    })

  }

}

// 使用

store.dispatch('actionA').then(() => {

  // ...

})

// 其他action

actions: {

  // ...

  actionB ({ dispatch, commit }) {

    return dispatch('actionA').then(() => {

      commit('someOtherMutation')

    })

  }

}

```

#### async/wait

```js

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {

  async actionA ({ commit }) {

    commit('gotData', await getData())

  },

  async actionB ({ dispatch, commit }) {

    await dispatch('actionA') // 等待 actionA 完成

    commit('gotOtherData', await getOtherData())

  }

}

```

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

### Module

1. 简单模式

```js

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 的状态

```

2. 模块的局部状态

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

```js

const moduleA = {

  state: { count: 0 },

  mutations: {

    increment (state) {

      // 这里的 `state` 对象是模块的局部状态

      state.count++

    }

  },

  getters: {

    doubleCount (state) {

      return state.count * 2

    }

  }

}

```

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

```js

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

    }

  }

}

```

3. 命名空间

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

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

```js

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']

          }

        }

      }

    }

  }

})

```

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

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

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

```js

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) { ... }

    }

  }

}

```

3. 在带命名空间的模块注册全局 action

> 若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中

```js

{

  actions: {

    someOtherAction ({dispatch}) {

      dispatch('someAction')

    }

  },

  modules: {

    foo: {

      namespaced: true,

      actions: {

        someAction: {

          root: true,

          handler (namespacedContext, payload) { ... } // -> 'someAction'

        }

      }

    }

  }

}

```

4. 带命名空间的绑定函数

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

```js

computed: {

  ...mapState({

    a: state => state.some.nested.module.a,

    b: state => state.some.nested.module.b

  })

},

methods: {

  ...mapActions([

    'some/nested/module/foo', // -> this['some/nested/module/foo']()

    'some/nested/module/bar' // -> this['some/nested/module/bar']()

  ])

}

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

computed: {

  ...mapState('some/nested/module', {

    a: state => state.a,

    b: state => state.b

  })

},

methods: {

  ...mapActions('some/nested/module', [

    'foo', // -> this.foo()

    'bar' // -> this.bar()

  ])

}

```

5.使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。它返回一个对象,对象里有新的绑定在给定命名空间值上的组件绑定辅助函数

```js

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'

    ])

  }

}

```

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,920评论 0 7
  • 使用说明-Vuex 安装 直接下载 / CDN 引用 Unpkg.com 提供了基于 NPM 的 CDN 链接。以...
    满是裂缝的花卷阅读 975评论 0 8
  • Vuex 的学习记录 资料参考网址Vuex中文官网Vuex项目结构示例 -- 购物车Vuex 通俗版教程Nuxt....
    流云012阅读 1,444评论 0 7
  • State 单一状态树 Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“...
    peng凯阅读 682评论 2 0
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 3,089评论 0 6