vuex 使用文档小结篇(2)
通过在根实例中注册 store 选项,该store 实例会注册入到跟组件下的所有子组件,且子组件能通过 this.$store 访问到。更新 counter 的实现:
const Counter = {
template : '<div>{{ count }}</div>',
computed: {
count this.$store.state.count
}
}
mapState 辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些冗余。
为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。
// 在单独构建的版本中辅助函数为 Vuex.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
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([ // 映射 this.count 为 store.state.count 'count' ])
组件仍然保有局部状态。
Getters
有时候我们需要从store 中的state 中 的state 中派生一些状态,列如对列表进行过滤并计算。
computed: {
doneTodosCount() {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
Vuex 允许我们再store 中定义getters (可以认为是stroe 的计算属性)
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)
}
}
})
内容版权声明:除非注明,否则皆为本站原创文章。
