Vuex核心概念之State

1. 通过在根组件挂载 store 对象,这样根组件以及所有子组件都可以使用 store 中的全局属性.

例如我们在 vuex store 全局管理一个 state 中的 count 属性,

那么在组件中,可以直接在 Mustache 语法【双大括号】中直接使用 $store.state.count ,但是如果多次调用此属性,那么会显得过于繁琐。因此我们可以将其利用 computed 属性返回,如下:

    computed: {
      count() {
        return this.$store.state.count;
      }
    }

2. mapState 辅助函数:假如我们希望获取多个状态,将这些属性一个个声明在 computed 计算属性里也显得过于繁琐,那么此时我们可以引入一个 mapState 辅助函数来帮助我们去获取.

    import {mapState} from 'vuex'
    computed: mapState({
      count: state => state.count,
      message: state => state.message
    })
<template>
  <div>
    <h2>{{count}}</h2> 
    <h2>{{message}}</h2>
  </div>
</template>

3. 那么如果我们不希望 computed 计算属性从 vuex 中获取属性,这个组件本身也需要计算属性,我们如何将 mapState 和 自身计算属性 结合使用呢?

其实由上面用法示例也可以看出 mapState 返回的是一个对象,我们需要将原本的 computed 对象 和 mapState 对象 结合到一个对象里,考虑使用 Object.assgin(dest, ...srcs)

我们自身计算属性有一个 myComputed, 后面的 mapState 就是从 vuex 中导入的属性.

    computed: Object.assign({
      myComputed() {
        return 'myComputed';
      }
    }, mapState({
      count: state => state.count,
      message: state => state.message
    })),
<template>
  <div>
    <h2>{{count}}</h2>
    <h3>{{ myComputed }}</h3>
    <h2>{{message}}</h2>
  </div>
</template>

简洁形式:利用ES6对象展开运算符 三个点...

    computed: {
      myComputed() {
        return 'myComputed';
      },
      ...mapState({
        count: state => state.count,
        message: state => state.message
      })
    },

4. 官方文档注意点:

组件仍然保有局部状态

使用 Vuex 并不意味着你需要将所有的状态放入 Vuex。虽然将所有的状态放到 Vuex 会使状态变化更显式和易调试,但也会使代码变得冗长和不直观。如果有些状态严格属于单个组件,最好还是作为组件的局部状态。你应该根据你的应用开发需要进行权衡和确定

posted @ 2021-09-21 22:09  TwinkleG  Views(229)  Comments(0)    收藏  举报