[Vuejs]-Dynamically loop on keys of object

0👍

you have to take all keys in one array then you can bind it.

obj: {
address: 'street test 123',
fine: '32 PHP',
magic: 'Love'
}

var keys = Object.keys(obj);


<div>
    <span>{{keys.join(,)}}</span>
</div>

0👍

You can just loop through the whole object like this, here index is the variable name and item is the value

var app4 = new Vue({
  el: '#app-4',
  data: {
    obj: {
      address: 'street test 123',
      fine: '32 PHP',
      magic: 'Love'
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app-4">
<div v-for="(item, index) in obj">
    <span>{{item}}</span>
</div>
</div>

0👍

I don’t think you want to use v-for for this purpose.

This is what I would do without changing how you have your obj set up:

<div id="foo">
  {{computedVal}}
</div>

and in the Vue instance,

new Vue({
   data: {
     // ... miscellaneous stuff
     obj: {
       prop1: 'val1',
       prop2: 'val2',
       prop3: 'val3',
     }
   },
   methods:{ /* ... */ },
   computed: {
      computedVal(){
        let str = '';
        for(let key in this.obj){
          let val = this.obj[key];
          str += `<span>${key} : ${val}</span>`;
        }
        return str;
      }
   }
});

This will be your output:

<div id="foo">
   <span>prop1 : val1</span>
   <span>prop2 : val2</span>
   <span>prop3 : val3</span>
</div>

Of course you can do this inside v-for as well.

My understanding is that as of now, Vue doesn’t do object property iteration inside v-for.

Leave a comment