Vue v-for 指令

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2023年8月8日 (二) 06:51的版本 →‎总结
跳到导航 跳到搜索

https://www.bilibili.com/video/BV12J411m7MG/?p=15

根据数据生成列表结构

形式1:

<div id="app">
    <ul>
        <li v-for="item in arr">
            你好
        </li>
    </ul>
</div>

形式2:

<div id="app">
    <ul>
        <li v-for="item in arr" :title="item">
        {{item}}
        </li>
    </ul>
</div>

形式3:

<div>
    <ul>
        <li v-for="(item,index) in arr" :title="item">
        {{index}}{{ item }}
        </li>
    </ul>
</div>

对于对象:

<div id="app">
    <ul>
        <li v-for="(item,index) in objArr">
        {{item.name}}
        </li>
    </ul>
</div>
var app = new Vue({
    el:"#app",
    data:{
        arr:[1,2,3,4,5],
        objArr:[
            {name:"jack"},
            {name:"rose"}
        ]
    }
})

完整代码示例:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>v-for 指令</title>
    </head>
    <body>
        <div id="app">
            <input type="button"  value="添加数据" @click="add">
            <input type="button"  value="移除数据" @click="remove">

            <ul>

                <li v-for="item in arr">
                    hello world {{ item }}
                </li>
                <li v-for="it in arr">
                    hello world {{ it }}
                </li>
                <li v-for="(it,index) in arr">
                    {{index}} hello world {{ it }}
                </li>
                <li v-for="(it,index) in arr">
                    {{index+1}} hello world {{ it }}
                </li>

                <h2 v-for="item in vegetables" v-bind:title="item.name">
                    {{ item.name }}
                </h2>
            </ul>
        </div>

        <!-- 开发环境版本,包含了有帮助的命令行警告 -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app",
                data:{
                    arr:["北京","上海","广州","深圳"],
                    vegetables:[
                        {name:"西兰花炒蛋"},
                        {name:"蛋炒西兰花"}
                    ]
                },
                methods:{
                    add: function() {
                        this.vegetables.push({name:"花菜炒蛋"})
                    },
                    remove: function() {
                        this.vegetables.shift();
                    }
                }
            })
        </script>

    </body>
</html>

总结

  • v-for 指令的作用是:根据数据生成列表结构
  • 数组经常和 v-for 结合使用
  • 语法是 (item, index) in 数据
  • item 和 index 可以结合其他指令一起使用