如何在v-for循环中通过动态key获取Vuex mapGetters数据?
解决方案
你当前的问题在于模板取值逻辑错误:topicList是字符串数组,循环得到的topic是单个键名字符串而非对象,同时无法直接通过字符串键名访问mapGetters映射的计算属性。这里提供两种简洁的解决方式:
方式一:直接通过$store.getters访问
mapGetters本质是将Vuex的getters映射为组件计算属性,你可以跳过映射步骤,直接在模板中通过键名字符串访问$store.getters对应数据:
<template> <v-row> <v-col cols="12" sm="6" md="6" lg="4" v-for="(topicKey, index) in topicList" :key="index"> <v-card class="mx-auto" max-width="400" outlined> <v-list-item three-line> <v-list-item-content> <!-- 显示键名 --> <div class="text-overline">{{ topicKey }}</div> <v-list-item-title class="text-h6 mb-1"> <!-- 通过键名字符串获取Vuex getter数据 --> {{ $store.getters[topicKey] }} </v-list-item-title> <div class="text-overline">Value</div> <v-list-item-subtitle>Timestamp</v-list-item-subtitle> </v-list-item-content> </v-list-item> </v-card> </v-col> </v-row> </template> <script> import { mapActions, mapGetters } from "vuex"; export default { data: () => ({ topicList: [ "KL_LT1_PM_M6_ACTKWH", "KL_LT1_PM_M6_ApparentPower", ], }), // 若不需要单独调用这些getter,可删除mapGetters映射 computed: { ...mapGetters([ "KL_LT1_PM_M6_ACTKWH", "KL_LT1_PM_M6_ApparentPower", "KL_LT1_PM_M6_AVGCUR", ]), }, }; </script>
方式二:通过计算属性整理getter数据
如果希望保留mapGetters映射,可新增一个计算属性,将需要的getter数据整理为键值对对象,再通过循环的键名取值:
<template> <v-row> <v-col cols="12" sm="6" md="6" lg="4" v-for="(topicKey, index) in topicList" :key="index"> <v-card class="mx-auto" max-width="400" outlined> <v-list-item three-line> <v-list-item-content> <div class="text-overline">{{ topicKey }}</div> <v-list-item-title class="text-h6 mb-1"> <!-- 从整理好的对象中取值 --> {{ topicData[topicKey] }} </v-list-item-title> <div class="text-overline">Value</div> <v-list-item-subtitle>Timestamp</v-list-item-subtitle> </v-list-item-content> </v-list-item> </v-card> </v-col> </v-row> </template> <script> import { mapGetters } from "vuex"; export default { data: () => ({ topicList: [ "KL_LT1_PM_M6_ACTKWH", "KL_LT1_PM_M6_ApparentPower", ], }), computed: { ...mapGetters([ "KL_LT1_PM_M6_ACTKWH", "KL_LT1_PM_M6_ApparentPower", "KL_LT1_PM_M6_AVGCUR", ]), // 整理需要的getter数据为键值对对象 topicData() { return this.topicList.reduce((result, key) => { result[key] = this[key]; return result; }, {}); }, }, }; </script>
关键说明
- 你原模板中
{{ topic.topic }}和{{ topic.value }}写法错误,因为循环变量topic是字符串类型的键名,并非包含topic、value属性的对象。 - 两种方式都能通过循环的键名字符串动态获取对应Vuex getter数据,可根据实际需求选择。
内容的提问来源于stack exchange,提问作者Mirza Aditya Deliantama
相关产品推荐
相关产品推荐

