How to loop through object in vuejs html template

JavaScript |

12th May, 2023

Click here to share

In Vue.js, you can loop through an object using the v-for directive in the HTML template. Here's an example:

<template>
  <div>
    <ul>
      <li v-for="(value, key) in myObject" :key="key">
        {\{ key }}: {\{ value }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      myObject: {
        name: 'John',
        age: 30,
        city: 'New York'
      }
    }
  }
}
</script>

 

In this example, we have an object called myObject that contains three properties: name, age, and city. We use the v-for directive to loop through the object and display each property and its value in a list.

The v-for directive takes two parameters: the first parameter is the value of the current iteration, and the second parameter is the key of the current iteration. We use these parameters to display the key-value pairs of the object.

We use the :key directive to set a unique key for each item in the list. This helps Vue.js keep track of the items in the list and update the DOM efficiently.

Leave a Reply

RELATED POSTS


Total of 0 Comment