Home > database >  Vuejs Access data values dynamically
Vuejs Access data values dynamically

Time:09-21

I don't know if this is a logical question, however, I have a weird issue or say a weird requirement. I need to access the value of a dynamically generated variable.

  data:{
        brand: undefined,
        model: undefined
   }
    
   methods:{
          check(){
              let fields = ['brand', 'model'];
              for(let i in fields){
                 console.log(`this.${fields[i]}`) // I need this to access the field values
               }
           }
     }

CodePudding user response:

You can just nest the bracket notation, i.e. this[fields[i]]. See proof-of-concept below:

// Suppress annoying console.info
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    brand: 'foobar brand',
    model: 'acme model'
  },

  methods: {
    check() {
      let fields = ['brand', 'model'];
      for (const i in fields) {
        console.log(this[fields[i]]);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"><button type="button" @click="check">Check button</button></div>

Even better: you can use for...of for modern browsers, which avoids the need of a nested bracket notation (improves readability, if it helps):

// Suppress annoying console.info
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {

    brand: 'foobar brand',
    model: 'acme model'
  },

  methods: {
    check() {
      let fields = ['brand', 'model'];
      for (const field of fields) {
        console.log(this[field]);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"><button type="button" @click="check">Check button</button></div>

  • Related