您的位置:首页 > 产品设计 > UI/UE

vuex学习四----getters

2017-07-24 10:59 113 查看
1:有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并且计数;

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


如果有多个组件需要用的这个属性,我们要么复制这个函数;或者抽取到一个共享函数然后再多出导入它;这2种方式都不理想

2:VUEX允许我们在store中定义getters,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


Getters也可以接受其他getters最为第二个参数:

getters:{
doneTodosCount:(state,getters)=>{
return getters.doneTodos.length;
}
}


我们可以很容易的在任何组建中使用它:

computed:{
doneTodosCount(){
return this.$store.getters.doneTodosCount
}
}


3:mapGetters辅助函数

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

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


如果你想讲一个getters属性另外娶一个名字,使用对象的形式:

mapgetters({
//映射this.doneCount为store.getters.doneTodosCount
doneCount:'doneTodosCount'
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: