上一篇:Mutations-mutations 下一篇:State-state
Getters-getters
Getters
有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数:
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果有多个组件需要用到此属性,我们要么复制这个函数,或者抽取到一个共享函数然后在多处导入它 —— 无论哪种方式都不是很理想。
Vuex 允许我们在 store 中定义『getters』(可以认为是 store 的计算属性)。Getters 接受 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)
}
}
})
Getters 会暴露为 store.getters
对象:
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
Getters 也可以接受其他 getters 作为第二个参数:
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
我们可以很容易地在任何组件中使用它:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
mapGetters
辅助函数
mapGetters
辅助函数仅仅是将 store 中的 getters 映射到局部计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({
// 映射 this.doneCount 为 store.getters.doneTodosCount
doneCount: 'doneTodosCount'
})
- 加入Vue.js社区-join
- 从 Vue Router 0.7.x 迁移-migration-vue-router
- 从 Vue 1.x 迁移-migration
- 状态管理-state-management
- 路由-routing
- 插件-plugins
- 混合-mixins
- 过渡状态-transitioning-state
- 过渡效果-transitions
- 表单控件绑定-forms
- 事件处理器-events
- Class 与 Style 绑定-class-and-style
- 计算属性-computed
- vuejs介绍
- 与Vue.js相关的精彩开发案例 vuejs开发例子
- 对组件注入component-injections
- Router 实例router-instance
- Router 构造配置options
- 路由信息对象route-object
- router-viewrouter-view
- router-linkrouter-link
- 懒加载lazy-loading
- 滚动行为scroll-behavior
- 数据获取data-fetching
- 过渡动效transitions
- 路由元信息meta
- 导航钩子navigation-guards
- HTML5 History 模式history-mode
- 重定向 和 别名redirect-and-alias
- 命名视图named-views
- 命名路由named-routes
- 编程式导航navigation
- 嵌套路由nested-routes
- 动态路由匹配dynamic-matching
- 开始getting-started
- 安装installation
- Introductionzh-cn