【Vue】通过v-for循环在html元素中渲染应用(图文+完整示例)

 

<!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>demo</title>
</head>
<script type="text/javascript" src="vue.js"></script>

<body>
    <div id="box">

        ---- 遍历数组:第1种写法 ---- <br>
        <ul>
            <li v-for="p in persons" :key="p.id">
               {
   
   {p.id}}  {
   
   {p.name}}-{
   
   {p.age}}岁
            </li>

        </ul>

        ---- 遍历数组:第2种写法 ---- <br>
        <ul>
            <li v-for="(p,index) in persons" :key="index">
               {
   
   {index}}  {
   
   {p.name}}-{
   
   {p.age}}岁
            </li>

        </ul>

        ---- 遍历对象:(键值,键名) ---- <br>
        <ul>
            <li v-for="(value,name) in car" :key="name">
               {
   
   {index}}  {
   
   {name}}:{
   
   {value}}
            </li>

        </ul>


    </div>
</body>
<script type="text/javascript">
    var box = new Vue({
        el: "#box",
        data: {
            persons: [
                {
                    id: "01",
                    name: "张飞",
                    age: 20
                },
                {
                    id: "02",
                    name: "刘备",
                    age: 30
                },
                {
                    id: "03",
                    name: "吕布",
                    age: 22
                }
            ],
            car:{name:"红旗",color:"黑色",price:"50万"}
        }
    })
</script>

</html>

猜你喜欢

转载自blog.csdn.net/dxnn520/article/details/123078789