核心概念--Getter

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

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

(1) 通过属性访问

  • Getter 会暴露为 store.getters 对象,你可以以属性的形式访问这些值:
  store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
  • Getter 也可以接受其他getter 作为第二个参数:
  getters: {
     // ...
     doneTodosCount: (state, getters) => {
        return getters.doneTodos.length;
     }
  }

  store.getters.doneTodosCount // 1
  • 我们可以很容易的在任何组件中使用它:
  computed: {
     doneTodosCount (){
        return this.$store.getters.doneTodosCount;
     }
  }

(2) 通过方法访问

你也可以通过让 getter 返回一个函数,来实现给 getter 传参

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

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

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

(3) mapGetters 辅助函数

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

import { mapGetters } from 'vuex'

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

经过 mapGetters 函数调用后的结果,如下所示:

import { mapGetters } from 'vuex'
export default {
  // ...
  computed: {
    doneTodosCount() {
      return this.$store.getters['doneTodosCount']
    },
    anotherGetter() {
      return this.$store.getters['anotherGetter']
    }
  }
}

再看一个参数 mapGetters 参数是对象的例子:

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

经过 mapGetters 函数调用后的结果,如下所示:

computed: { 
   doneCount() { 
      return this.$store.getters['doneTodosCount'] 
   } 
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,645评论 8 265
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,664评论 0 5
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  •   面向对象(Object-Oriented,OO)的语言有一个标志,那就是它们都有类的概念,而通过类可以创建任意...
    霜天晓阅读 2,140评论 0 6
  • 忘记一个人需要几天?我不知道,但正在经历这样一个过程。我知道,总归会过去的吧,或早或晚而已。只是还在遗憾,还在留恋...
    才子难装阅读 600评论 0 0