vuex学习四----getters
2017-07-24 10:59
113 查看
1:有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并且计数;
如果有多个组件需要用的这个属性,我们要么复制这个函数;或者抽取到一个共享函数然后再多出导入它;这2种方式都不理想
2:VUEX允许我们在store中定义getters,getters接受state作为他的第一个参数;
Getters会暴露为store.getters的对象
Getters也可以接受其他getters最为第二个参数:
我们可以很容易的在任何组建中使用它:
3:mapGetters辅助函数
mapGetters辅助函数仅仅是将store中的getters映射到局部计算属性
如果你想讲一个getters属性另外娶一个名字,使用对象的形式:
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' })
相关文章推荐
- Vuex的Getter学习
- vuex所有核心概念完整解析State Getters Mutations Actions
- Vuex学习之-- 在组件中提交 Mutation
- Vuex入门学习手册
- vuex所有核心概念完整解析State Getters Mutations Actions
- vuex学习六----actions
- Vue.js学习系列二 —— vuex学习实践笔记(附DEMO)
- Vuex的State学习
- vue2学习笔记一、根据环境改变常量、vuex中mapGetters只能在组件created之后使用
- vuex学习笔记
- vuex状态管理模式之Getters属性
- Vue.js学习系列二 —— vuex学习实践笔记(附DEMO)
- Vuex的学习笔记一
- 学习vuex
- vuex学习心得
- Vue.js学习系列二 —— vuex学习实践笔记(附DEMO)
- Vue.js学习系列二 —— vuex学习实践笔记(附DEMO)
- vuex学习
- vue学习笔记-vuex
- vue学习 之 vuex安装及使用