Vuex的核心概念主要有5点,分别是:State、Getter、Mutation、Action、Module
1.State
Vuex使用单一状态树,用一个对象就包含了全部的应用层级状态。意味着每个应用将仅仅包含一个store实例。单一状态树能让我们直接定位任一特定的状态片段。
由于Vuex的状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性(computed)中返回某个状态。(这种模式导致组件依赖全局状态单例)。因此,Vuex通过store选项,提供了一种机制将状态从根组件“注入”到每一个子组件中。如下:
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
通过在根实例中注册store选项,该store实例会注入到根组件下的所有子组件中,且子组件能通过this.$store访问到。更新Counter的实现:
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
2.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
}
})
}
网友评论