A
A
Artem Prokhorov2022-01-26 14:51:09
Vue.js
Artem Prokhorov, 2022-01-26 14:51:09

How to specify the name of a variable from data in a template in a loop?

<div v-for="(elem, key) in data" :="key">{{ elem }}</div

export default {
  data() {
    return {
      a: 1,
      b: "some",
      c: [1, 2, 3],
      data: ['a', 'b', 'c']
    }
  }
}

data in the loop is an array like this ['a', 'b', 'c'].
And I want the value of my variable to be displayed, not the string ab or c.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WapSter, 2022-01-26
@kotcich

<div
      v-for="(elem, key) in data"
      :key="key"
    >
      {{ $data[elem] }}
    </div>

D
Dmitry Gololobov, 2022-01-26
@dGololobov

At a glance, I see two options:
1. wrap your variables a, b, c in an object:

export default {
  data() {
    return {
      myVars: {
           a: 1,
           b: "some",
           c: [1, 2, 3],
      },
      data: ['a', 'b', 'c'],
    }
  }
}

<div v-for="(elem, key) in data" :="key">{{ myVars[elem] }}</div>

2. Make a method to get the values ​​of variables by their name:
export default {
  data() {
    return {
      a: 1,
      b: "some",
      c: [1, 2, 3],
      data: ['a', 'b', 'c'],
    }
  },
  methods: {
     getDataValue(param) {
            return this[param] || null;
      },
   },
}

<div v-for="(elem, key) in data" :="key">{{ getDataValue(elem) }}</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question