您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)vue中v-for指令怎么完成列表渲染,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
最基本的使用案例1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>列表渲染</title> <script src="../../js/vue.js"></script> </head> <body> <div id="app"> <ul> <li v-for="(name,index) in names"> {{index}}-{{name}} </li> </ul> </div> </body> <script> new Vue({ el:'#app', data() { return { names:['張三','李四','王五','趙六'] } }, }) </script> </html>
上面的例子中:通過v-for指令,綁定data中的names數(shù)組,以列表的形式遍歷出數(shù)組中的元素,其中name代表當(dāng)前數(shù)組的一個(gè)遍歷元素,index是當(dāng)前元素name在數(shù)組中的索引,輸出效果如下:
v-for還可以遍歷對象,字符串,指定數(shù)字等等。如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>列表渲染</title> <script src="../../js/vue.js"></script> </head> <body> <div id="app"> <!-- 遍歷對象 --> <ul> <li v-for="(propery,key) in student"> {{key}}:{{propery}} </li> </ul> <!-- 遍歷字符串 --> <ol> <li v-for="char in str">{{char}}</li> </ol> <!-- 自定義輸出 --> <ul> <li v-for="num in 10"> {{num}} </li> </ul> </div> </body> <script> new Vue({ el:'#app', data() { return { student:{ name:'李明', age:23, address:'大連' }, str:'HelloWord' } }, }) </script> </html>
上面代碼的效果如下:
作用:
key
是虛擬dom
對象的標(biāo)識,當(dāng)數(shù)據(jù)發(fā)生變化時(shí),vue
會(huì)根據(jù)【新數(shù)據(jù)】生成【新的虛擬dom】,隨后Vue進(jìn)行【新虛擬dom】和【舊虛擬dom】的差異對比
差異對比規(guī)則:
先是在【舊虛擬dom】中找到與【新虛擬dom】相同的key
(1)若虛擬dom
中的內(nèi)容沒變,直接使用之前的真實(shí)dom
(2)若虛擬dom
中的內(nèi)容邊了,則生成新的真實(shí)dom
,隨后替換掉頁面中之前的真實(shí)dom
若在【舊虛擬dom】中沒有找到和【新虛擬dom】相同的key,就創(chuàng)建新的真實(shí)dom,隨后渲染到頁面中
列表過濾即在進(jìn)行列表遍歷前對列表元素進(jìn)行一次篩選,選擇出符合要求元素進(jìn)行展示,如:
假如我們要過濾掉列表里名為‘張三'的人:(可以用computer或者watch這兩個(gè)屬性實(shí)現(xiàn))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>列表渲染</title> <script src="../../js/vue.js"></script> </head> <body> <div id="app"> <!-- 列表過濾 --> <!-- computer方式 --> <ul> <li v-for="(name,intdex) in showNames">{{name}}</li> </ul> <!-- watch方式 --> <ol> <li v-for="(name,index) in displayName">{{name}}</li> </ol> </div> </body> <script> new Vue({ el:'#app', data() { return { names:['張三','李四','王五','趙六'], displayName:[], } }, watch: { name:{ immediate:true, handler(val){ this.displayName=this.names.filter((n)=>{ return n!='張三' }) } } }, computed: { // 假如我們要過濾掉名為'張三'的人 showNames(){ return this.names.filter((n)=>{ return n!="張三" }) } }, }) </script> </html>
效果:
關(guān)于“vue中v-for指令怎么完成列表渲染”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。