[Vuejs]-Use string with this keyword in vuejs or javascript

1👍

use this :

  new Vue({
  el:'#app',
  data:{
    cars:[
      {
        name:'',
        make:''
      }
    ]
  },
  methods:{
    addToArray(nameOfTheArray){ 
      this[nameOfTheArray].push({
         name:'',
         make:''
      })
 }
  }
})

1👍

You can access to an object property by obj[key], also check if the key exists in the object to avoid runtime errors

 new Vue({
  el:'#example',
  data:{
    cars:[
      {
        name:'',
        make:''
      }
    ]
  },
  methods:{
    addToArray(nameOfTheArray){
      if (nameOfTheArray in this) {
        this[nameOfTheArray].push({
         name: 'default name',
         make: 'default make'
        })
      } else {
        alert('Invalid key!')
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>

<div id="example">
  <button type="button" @click="addToArray('cars')">Add to cars</button>
  <button type="button" @click="addToArray('invalidKey')">Add invalidKey</button>
  
  {{ cars }}
</div>
👤DobleL

Leave a comment