使用v-for
遍歷數(shù)組對象
我們可以用 v-for
指令基于一個數(shù)組來渲染一個列表双藕。v-for 指令需要使用book in books
形式的特殊語法,其中 books
是源數(shù)據(jù)數(shù)組阳仔,而 book
則是被迭代的數(shù)組元素的別名忧陪。具體操作如下代碼
data:{
books:[
{
name:"三國演義",
author:"羅貫中"
},
{
name:"西游記",
author:"吳承恩"
},
{
name:"水滸傳",
author:"施耐庵"
},
{
name:"紅樓夢",
author:"曹雪芹"
}
]
}
<table border="1">
<!--第一行-->
<tr>
<td>循環(huán)下標(biāo)</td>
<td>書名</td>
<td>作者</td>
</tr>
<!--books:要遍歷的數(shù)組元素 book:每一個要遍歷元素的別名,book想當(dāng)于是book里面的每一個對象-->
<!--除了book近范,還可以加一個下標(biāo):index in也可以改成of-->
<!--v-for既可以遍歷數(shù)組對象嘶摊,也可以遍歷普通對象-->
<tr v-for="(book,index) in books" v-bind:key="index">
<td>{{index}}</td>
<td>{{book.name}}</td>
<td>{{book.author}}</td>
</tr>
</table>
循環(huán)數(shù)組對象瀏覽器顯示如下
image.png
在
v-for
塊中,我們可以訪問所有父作用域的屬性评矩。v-for 還支持一個可選的第二個參數(shù)叶堆,即當(dāng)前項的索引。
<tr v-for="(book,index) in books" v-bind:key="index">
<td>{{index}}</td>
<td>{{book.name}}</td>
<td>{{book.author}}</td>
</tr>
使用v-for遍歷單個對象
data:{
site:{
url:"https://lqgjava.github.io/",
name:"凌楓博客",
server:"github"
}
}
<div v-for="(s,p,index) in site" v-bind:key="index">{{s}}--{{p}}--{{index}}</div>
單個對象遍歷瀏覽器顯示如下
image.png
你也可以提供第二個的參數(shù)為 property 名稱 (也就是鍵名):下面代碼的
p
就是鍵名
<div v-for="(s,p,index) in site" v-bind:key="index">{{s}}--{{p}}--{{index}}</div>
數(shù)組更新檢測
變異方法
Vue 將被偵聽的數(shù)組的變異方法進(jìn)行了包裹斥杜,所以它們也將會觸發(fā)視圖更新虱颗。這些被包裹過的方法包括:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
你可以打開控制臺,然后對前面例子的 books
數(shù)組嘗試調(diào)用變異方法蔗喂。比如 app.books.push({name:"斗破蒼穹",author:"天蠶土豆"})
上枕。
image.png