什么是Vuex(一)—— State、Getter

104 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式

安装Vuex后,创建一个store仅需一个初始state对象和一些mutation。就可以通过store.state来获取状态对象,以及通过store.commit()方法触发状态变更。

为了在Vue组件中访问 this.$store property,需要为Vue实例提供创建好的store。

new Vue({
  el: '#app',
  store: store,
})

触发变化也仅仅是在组件的 methods 中提交 mutation。能更明确地追踪到状态的变化

State

Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。

mapState 辅助函数

当一个组件需要获取多个状态的时候,使用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
    }
  })
}

Getter

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

Getter 接受 state 作为其第一个参数:

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

通过属性访问getter

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

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

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

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

通过方法访问getter

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

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

mapGetters 辅助函数

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

import { mapGetters } from 'vuex'

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