vuex getters

Vuex允许在store中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来。且只有当它的依赖值发生了改变才会被重新计算。store 中的getters可以作为公共函数或者公共过滤器使用

实例使用的都是全局注册store模式,调用对象this.$store

直接调用:
    computed: {
      doneTodosCount () {
        return this.$store.state.todos.filter(todo => todo.done).length
      }
    }
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会暴露为store.getters对象,可以直接以属性的形式访问这些值:
this.$store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getter 也可以接受其他 getter 作为第二个参数:
getters: {
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}
调用:
    this.$store.getters.doneTodosCount // -> 1

很容易地在任何组件中使用它:
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

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

可以通过让getter返回一个函数,来实现给getter传参,在对 store 里的数组进行查询时非常有用。
getters: {
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
调用:
    store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

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

mapGetters 辅助函数
mapState 与 mapGetters 的用法类似,都是简化state或者是getters的显示
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:

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

如果想将一个 getter 属性另取一个名字,使用对象形式:
...mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

当mapGetters([])内部是中括号时,标识填充的是字符串数组,每个字符串标识的就是一个定义在store中的getter

当mapGetters({})内部是大括号时,标识填充的是对象,是用当前实例的对象混入定义在store中的getter

你可能感兴趣的:(vuex)