This article will introduce to you how to loop an array and render a list of items in vuejs
. I hope it will be helpful to friends in need!
##v-for<strong></strong>
Directives
Vuejs Provides us with a
v-for directive for rendering a list of items into the
dom.
v-for<strong></strong>
Syntax of the directive
v-for="user in users" <!-- user variable is iterator --> <!--users is data array-->
<template> <ul> <!-- list rendering starts --> <li v-for="user in users">{{user.name}}</li> </ul> </template> <script> export default{ data:function(){ return{ users:[ {id:1,name:"king"}, {id:2,name:"gowtham"}, {id:3,name:"ooops"}, ] } } } </script>
v-for instruction to loop through the
users array, so that in each loop the
user variable points to a different object that appears in the array.
key<strong></strong>
Attribute
v-for directive, we need to add a
key attribute to the element because
vuejs needs to track the list item based on the provided
key.
<template> <ul> <li v-for="user in users" :key="user.id"> {{user.name}} </li> </ul> </template> <script> export default{ data:function(){ return{ users:[ {id:1,name:"king"}, {id:2,name:"gowtham"}, {id:3,name:"ooops"}, ] } } } </script>
users array, the id attribute is unique to each object, so we pass it to the
key attribute.
<template> <ul> <li v-for="(user,index) in users" :key="user.id"> {{user.name}} {{index}} </li> </ul> </template>
Iterating over objects
We can also loop overJavaScript objects by using the
v-for directive.
<template> <ul> <!-- accessing `value and key` present in person object --> <li v-for="(value, key) in person" :key="key"> {{key}} : {{ value }} </li> </ul> </template> <script> export default { data: function() { return { person: { firstName: "Rim", lastName: "Doe", age: 20, eyeColor: "blue" } }; } }; </script>
value first, and then the
key.
The above is the detailed content of Use of v-for list rendering instructions in Vue.js (code example). For more information, please follow other related articles on the PHP Chinese website!