在vue文件中,template的作用是模板占位符,可幫助開發(fā)者包裹元素,可創(chuàng)建組件模板內(nèi)容;但在循環(huán)過程當(dāng)中,template不會(huì)被渲染到頁面上。
本教程操作環(huán)境:windows7系統(tǒng)、vue2.9.6版,DELL G3電腦。
Vue中template的作用及使用
先來看一個(gè)需求:下圖p用v-for做了列表循環(huán),現(xiàn)在想要span也一起循環(huán),應(yīng)該怎么做?
有3種方法可以實(shí)現(xiàn)
①:直接用v-for對(duì)span也循環(huán)一次(該方法雖然可以使用,但不要用這種方式,因?yàn)橐院竽銜?huì)哭)
②:在p和span外面包裹一個(gè)p,給這個(gè)p加循環(huán)(該方法會(huì)額外增加一個(gè)多余的p標(biāo)簽)
③:若你不想額外增加一個(gè)p,此時(shí)應(yīng)該使用template來實(shí)現(xiàn)(推薦)
template的作用是模板占位符,可幫助我們包裹元素,但在循環(huán)過程當(dāng)中,template不會(huì)被渲染到頁面上
DEMO
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>v-for</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <template v-for="(item, index) in list" :key="item.id"> <div>{{item.text}}--{{index}}</div> <span>{{item.text}}</span> </template> </div> <script> var vm = new Vue({ el: '#app', data: { list: [ { id: "010120", text: "How" }, { id: "010121", text: "are" }, { id: "010122", text: "you" } ] } }) </script> </body> </html>
【