Home > Net >  VueJS: How to call a variable from string instead of direct variable name in a template?
VueJS: How to call a variable from string instead of direct variable name in a template?

Time:12-30

How to call a variable set in <script> from the template using its string name?

For instance, in the example below, I'd like to call the foo variable using table[0]:

<template>
  <div>
    {{ table[0] }}
    {{ table[1] }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      foo: 'Hello World!',
      bar: '大家好!',
      table: ['foo', 'bar']
    }
  }
}
</script>

CodePudding user response:

By using $data, like {{ $data[table[0]] }}

CodePudding user response:

You can use copmputed property:

new Vue({
  el: '#demo',
  data() {
    return {
      foo: 'Hello World!',
      bar: '大家好!',
    }
  },
  computed: {
    table() {
      return [this.foo, this.bar]
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div>
    <div>{{ table[0] }}</div>
    <div>{{ table[1] }}</div>
  </div>
</div>

  • Related