vuex总结
多个组件共享数据时存在的问题:
1、嵌套传递数据流程繁琐
2、父子组件改变状态存在多分拷贝
引入vuex:一种为vue.js开发的状态管理模式
安装
npm install vuex --save
state
引用
这种模式导致所有组件依赖全局单例,每个使用state的组件都需要频繁引入,并且在测试组件时候改变状态。
通过Vuex的store选项,提供了一种将状态从根组件注入每个子组件的机制
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
……
})
子组件通过this.$store来访问状态,且将state声明为计算属性供组件使用
computed: {
count () {
return this.$store.state.count
}
}
但是声明多个状态时显得繁琐,此时可以使用mapState来简化引入。
getter
有时候我们需要从 store 中的 state 中派生出一些状态,使用getter可以减少重复对state进行处理
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)