Home > Software engineering >  How can i get the object value, when the key is on another variable v-for
How can i get the object value, when the key is on another variable v-for

Time:12-20

i want to ask a question. I have many data that stored in vuex and i want to use v-for to loop the card with the array of the object keys. How do i get the data in mapGetters when the key is on the v-for loop? I have tried the v-for with the key passing into curly braces. Code is below

<template>
  <v-row>
    <v-col cols="12" sm="6" md="6" lg="4" v-for="(topic, index) in topicList" :key="index">
      <v-card  max-width="400" outlined>
        <v-list-item three-line>
          <v-list-item-content>
            <div >{{ topic.topic }}</div> // value topic from the map getters
            <v-list-item-title >
              {{ topic.value }} // value from the map getters
            </v-list-item-title>
            <div >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: () => {
    return {
      topicList: [ //object keys array
        "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",
    ]),
  },
};
</script>

Thankyou for the answer :)

CodePudding user response:

You can try using it as {{ [topic].topic }} and {{ [topic].value }}

CodePudding user response:

import { mapGetters } from 'vuex'

const prefix = 'KL_LT1_PM_M6_'
const topicList = ['ACTKWH', 'ApparentPower'].map((topic) => `${prefix}${topic}`)

export default {
  computed: {
    ...mapGetters([...topicList, `${prefix}AVGCUR`]),
    topicList: () => topicList,
    getTopic() {
      return (topic) => this[topic] || {}
    }
  }
}
<v-col v-for="topic in topicList" :key="topic">
  ...
    <div >{{ getTopic(topic).topic }}</div>
    <v-list-item-title>{{ getTopic(topic).value }}</v-list-item-topic>
</v-col>

Most likely, your store could be greatly streamlined and, along with it, the components consuming it but, since you haven't shown it, I can't help you with that.

Note: if the above doesn't help you, there's likely a problem with your getters (try using them directly:

<pre 
  v-text="JSON.stringify({ KL_LT1_PM_M6_ACTKWH, KL_LT1_PM_M6_ApparentPower }, null, 2)"
/>

and see what you get).
If you need more help, consider adding a runnable minimal reproducible example, using codesandbox or similar.


Another note: moved topicList from data (e.g: data: () => ({ topicList })) to computed. There's no need for it to be reactive, it's a static list of strings. If you need it reactive (e.g: prefix or list are actually dynamic), move it back into data.

  • Related