當我們有一組數據需要進行渲染時,就可以通過v-for來完成
1、遍歷數組
<!--在遍歷的過程中,沒有用到索引值--> <ul> <li v-for="item in names">{{item}}</li> </ul> <!--在遍歷的過程中,獲取下標值--> <ul> <li v-for="(item,index) in names"> {{index+1}} . {{item}} </li> </ul> const app = new Vue({ el: "#app", //用於掛載要管理的元素 data: { //定義數據 message: 'hello', names: ['tom','jerry','marry'] } })
2、v-for遍歷對象
<div id="app">
<!--1、在遍歷對象的過程中,如果只是獲取一個值,那么獲取到的就是value-->
<ul>
<li v-for="item in info">{{item}}</li>
</ul>
<!--2、獲取key和value-->
<ul>
<li v-for="(value,key) in info">
{{key}}: {{value}}
</li>
</ul>
<!--3、獲取 value,key,index-->
<ul>
<li v-for="(value,key,index) in info">
{{index}} - {{key}}: {{value}}
</li>
</ul>
</div>
const app = new Vue({
el: "#app", //用於掛載要管理的元素
data: { //定義數據
info: {
name: '后臣',
age: 23,
height: 180
}
}
})
3、v-for使用過程中添加key
<ul> <!-- 保證key中的內容和要展示的內容是一一對應的 key的作用是為了高效的更新虛擬DOM --> <li v-for="item in letters" :key="item"> {{item}} </li> </ul>
