Vue 之 Vuex(3)mapState 的使用

mapState 是用来简化 computed 计算属性的一种写法,下面做一个对比:

  • 未使用之前
computed: {
      count() {
        return this.$store.state.count
      }
    },
  • 使用mapState之后
computed: {
      ...Vuex.mapState([
        'count'
      ]),
    }

具体使用见下面代码详情


<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
    <meta charset="UTF-8">
    <title>Vuex:mapState 的使用</title>
</head>
<body>
<div id="app">
    <button-counter></button-counter>
</div>

<script src="vuex.js"></script>
<script src="vue.js"></script>
<script>
  Vue.component('ButtonCounter', {
    data() {
      return {
        localCount: 5
      }
    },
    computed: {
      ...Vuex.mapState([
        // 当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以使用简写
        // 与 count: state => state.count 作用相同
        'count'
      ]),
      ...Vuex.mapState({
        // 箭头函数可使代码更简练
        count: state => state.count,
        // 传字符串参数 'count' 等同于 `state => state.count`
        countAlias: 'count',
        // 为了能够使用 `this` 获取局部状态,必须使用常规函数
        countPlusLocalState(state) {
          return state.count + this.localCount
        }
      })
    },
    methods: {
      ...Vuex.mapMutations([
        'increment'
      ]),
    },
    template: `
      <div>
      <button @click="increment">You clicked me {{ count }} times.</button>
      <p>count: {{ count }}</p>
      <p>countAlias: {{ countAlias }}</p>
      <p>countPlusLocalState: {{ countPlusLocalState }}</p>
      </div>
    `
  })

  // 创建Vuex容器
  const store = new Vuex.Store({
    strict: true,
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      }
    }
  })

  new Vue({
    el: '#app',
    store
  });

</script>
</body>
</html>

在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值