首页 > 技术文章 > vuex中怎么把‘库’中的状态对象赋值给内部对象(三种方法)

yinghuochongfighter 2018-05-09 22:12 原文

一、通过computed的计算属性直接赋值

import store from '@/store/store'
    export default{
        name: 'count',
        data(){
            return{
              msg:'Hello Vuex'
            }
        },
        computed:{
          num(){
            return this.$store.state.num;
          }
        },
        store
}

  

二、通过mapState的对象来赋值

首先引入mapState对象(注意:这里mapState对象一定要用{}括起来,不然会报错)

import { mapState } from 'vuex'

然后在computed属性中写入方法

//ES5的写法
computed:mapState({
            num:function(state){
               return state.num;
            }
}),
//ES6的写法
computed:mapState({
      num:state=>state.num
}),

三、通过mapState的数组来赋值(最常用的方法)

 computed:mapState(['num']),

 

四、总结,同理我们也可以通过mapMutations 的数组形式来获取state的方法,进而取代$store.commit('')的原始形式。

 

推荐阅读