vuex (3)

Getter

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

computed: {
  doneTodosCount{

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

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

Vuex 允许我们在store 中定义“getter” (可以认为是store的计算属性)

 

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

const store = createStore({

   state: {
      todos: [
           {id: 1,  text: '...',  done:true},
           {id: 2,  text: '...',  done:false}
      ]
   },

   getters: {
      doneTodos: (state) => {
            return state.todos.filter(todo => todo.done)
      }
   }
})

 

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

...

getters: {

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

...

 

通过属性访问

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

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

 

通过方法访问

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

...
getters: {
   // ...
   getTodoById: (state) => (id) => {

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

 

 store.getters.getTodoById(2)

 

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

 

mapGetters 辅助函数

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

 

posted on 2022-02-11 08:45  zhishiyv  阅读(30)  评论(0编辑  收藏  举报

导航