Vuex中的辅助函数mapState,...mapState对象展开符学习笔记

本文深入探讨了Vue中Vuex的mapState辅助函数,通过对比直接访问state与使用mapState的方式,展示了mapState如何简化代码并提高可读性。同时介绍了...mapState的使用场景,帮助开发者更好地理解和运用这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近找了个项目来练习,发现项目中有几处出现…mapState函数,遂去官网查看文档以及各路大佬分享的经验之谈,于是准备写点东西加深印象。

关于Vuex可前往官网查看更多内容,开始正文
mapState是state的辅助函数,其实也就是state的语法糖

1.不使用mapState

// store.js

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 1,
  },

mutations: {
    increment(state) {
      state.count += 1;
    },
    decrement(state) {
      state.count -= 1;
    },
  },

在组件中调用vuex里state的内容
html

<template>
  <!--index.vue-->
    <div class="index">
      <button @click="inCrement">increment</button>
      count:{{count}}<br>
      <button @click="deCrement">decrement</button>
    </div>
</template>

js

computed: {
    count() {
      return this.$store.state.count; // 重点在这
    },
  },
  
  methods: {
    inCrement() {
      this.$store.commit('increment'); // 提交Vuex中mutation的increment
    },
    deCrement() {
      this.$store.commit('decrement'); // 提交Vuex中mutation的decrement
    },
  },

效果如下
在这里插入图片描述

  1. mapState
    先在组件中引入
import { mapState } from 'vuex';

其他代码保持不变,computed中的要做修改

computed: mapState({
    count: 'count', // 和上面的代码功能是一样的,但语法更简洁明了
  }),
  1. …mapState
    …是ES6中的扩展运算符,和上面的写法没多大差异,都是为了避免计算属性的重复和冗余
computed: {
    ...mapState({
      count: 'count',
    }),
  },

后语:其他的mapGetters,mapMutations,mapActions和以上内容同理

参考来源:https://blog.youkuaiyun.com/dkr380205984/article/details/82185740

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值