遍历数组

 v-for最常用的可能就是用来遍历数组,接受两个参数(item, index),item为遍历出的每组数据,index为每组数据的索引,可做唯一标识

    <div id="app">
 <ul>
    <!-- 1.在遍历的过程中,没有使用下标值(索引值) -->
    <!-- item是数组中的每一项,没有使用下标值(索引值) -->
    <li v-for="(item,index) in list">{{index}}-{{item}}</li>
 </ul>
    </div>
    <script src="../Vue/vue.js"></script>
    <script>
new Vue({
    el:'#app',
    data:{
        list:['刘备','关羽','张飞','赵云','黄总']
    }
})
    </script>
</body>
</html>

效果图:

  遍历对象

   v-for遍历对象可接受三个参数(value, key, index),value为每个对象的value值,key为key值,index为索引

 let vue = new Vue({
      el: "#app",
      data: {
        list: [
          { id: 1, name: "张狗", age: 88 },
          { id: 2, name: "舔狗", age: 20 },
          { id: 3, name: "藏獒", age: 10 },
          { id: 4, name: '狼狗', age: 18 }
        ],
       }

效果图:

遍历数字

<body>
    <div id="app">
        <!-- 遍历数字(指定次数的循环) -->
        <h2>以下是指定次数</h2>
        <ul>
            <!-- num是1到10 -->
            <li v-for="num in 10">{{num}}</li>
    
        </ul>
    </div>
    <script src="../Vue/vue.js"></script>
    <script>
new Vue({
    el:'#app'
    })
    </script>
</body>
</html>

效果图:

 

给 v-for 加 key属性

使用v-for 的时候,给对应的元素或组件添加上一个:key 属性,为了更好地复用,但是要保证这个 key 的值是唯一的

<body>
    <div id="app">
        <button @click="list.splice(1,0,{id:4,name:'小明'})">添加</button>
        <ul>
            <li v-for="item in list":key="item.id">
                <input type="checkbox" >
                <span>{{item.name}}</span>
            </li>
    
        </ul>
    </div>
  

    <script src="../Vue/vue.js"></script>
    <script>
new Vue({
    el:'#app',
    data:{
        list:[
            {id:1,name:'小红'},
            {id:2,name:'小张'}, 
            {id:3,name:'小黑'}
        ]
    }
    })
    </script>
</body>
</html>

效果图:

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐