美文网首页
32-Vuex-state

32-Vuex-state

作者: 早起的鸟儿 | 来源:发表于2019-10-31 08:53 被阅读0次

    state作为一个“唯一数据源”
    一、在 Vue 组件中获得 Vuex 状态
    1.直接方式

    {{$store.state.count}}
    

    2.利用计算属性:

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

    当一个组件需要多种状态的时候,用computed显得特别冗余,这时候我们就可以用辅助函数:mapState

    3.mapState

    • 数组形式
    import {mapState} from "vuex"  //引入
    computed: mapState([  //数组格式
        "num"  //可以是一个对象,数组
    ]),
    

    注意:计算属性的名称与 state 的中定义的数据名称相同时,可以传入数组格式。

    • 对象形式
    computed: mapState({
      // count: state => state.num   //箭头函数
      //等同于
      count (state) {   //state可以是一个对象,数组
         return state.num
      }
     // 为了能够使用 `this` 获取局部状态,必须使用常规函数
      countPlusLocalState (state) {
         return state.count + this.localCount
      }
    }),
    

    相关文章

      网友评论

          本文标题:32-Vuex-state

          本文链接:https://www.haomeiwen.com/subject/wiwcmctx.html