Vuex 通过 store
选项,提供了一种机制将状态从根组件“注入”到每一个子组件中,且子组件能通过 this.$store
访问
const app = new Vue({ el: '#app', // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件 store, components: { Counter },//子组件 template: ` <div class="app"> <counter></counter>//引用子组件 </div> ` }) //子组件 const Counter = { template: `<div>{{ count }}</div>`, computed: { count () { //调用state return this.$store.state.count } } }
mapState
当一个组件需要获取多个状态时候,使用 mapState
辅助函数帮助我们生成计算属性,mapState
函数返回的是一个对象:
// 在单独构建的版本中辅助函数为 Vuex.mapState import { mapState } from 'vuex' export default { //使用mapState 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' ])
对象展开运算符...
...工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed
属性
computed: { localComputed () { /* ... */ }, //使用对象展开运算符将此对象混入到外部对象中 ...mapState({ // ... }) }
组件仍然保有局部状态
var vmA = new Vue({ data: { privateState: {},//每个组件可以有自己的state sharedState: store.state } })