Vuex mapState的基本使用

mapState把Store中的state映射到组件中的计算属性

Store文件

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    msg: 'Hello world',
    count: 0
  },
  mutations:{
  },
  actions:{
  },
  modules:{
  }
})

vue文件

<template>
  <div>
    <p>count: {{count}}</p>
    <p>msg: {{msg}}</p>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed:{
    /**
      相当于
      count: state => state.count
      msg: state=> state.msg
     */
    ...mapState(['count','msg'])
  }
}
</script>

如果vue文件已经存在count msg属性使用对象形式生成计算属性

<template>
  <div>
    <p>count: {{num}}</p>
    <p>msg: {{message}}</p>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  computed:{
    /**
      相当于
      num: state => state.count
      message: state=> state.msg
     */
    ...mapState({num: 'count', message: 'msg'})

  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/leslie1943/p/13369604.html