[JS][Vue]學(xué)習(xí)記錄之v-for

Demo地址
先準(zhǔn)備這樣一個vue對象:

<script>
    var app = new Vue({
        el:'#app',
        data:{
            names:['allen','marry','tom'],
            person:
                [{name:'allen1',age:27},
                {name:'allen2',age:28},
                {name:'allen3',age:29},
                 ]
        }
    });
</script>

我們直接看下面的代碼:

    <lu>
        <!--names是vue中的數(shù)組,name是自定義的變量-->
        <li v-for="name in names">
            {{name}}<!--拿到name就可以顯示-->
        </li>
    </lu>
  
    <!--template 可以省略一些不必要的dom元素-->
    <template v-for="(user,index) in person">
         <!--index是下標(biāo),user是person的元素,person是vue中的數(shù)組-->
        {{index}}:{{user.name}}-{{user.age}}
    </template>
    <template v-for="user in person">
        <p v-for="(value,key) in user">
            value:{{value}} - key:{{key}}
        </p>
    </template>

代碼說明:

  • v-for="name in names",這個names代表的就是vue對象中的數(shù)組names,name是我們自己定義的一個變量.
  • v-for="(user,index) in person",其中personvue對象中的數(shù)組person,userperson中的對象元素,index是對象元素的下標(biāo).
  • "(value,key) in user",valuekeyuser里面的valuekey,通過這種方式可以拿到對應(yīng)需要的value或者key
  • template可以幫我們省略一些不必要的dom元素,例如我一個塊只用<span>就可以解決問題的,但是我多套了一層<div>,這個時候template就可以幫我們省略掉這個<div>了.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容