您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页[JS][Vue]学习记录之v-for

[JS][Vue]学习记录之v-for

来源:化拓教育网
<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中的数组,name是自定义的变量-->
        <li v-for="name in names">
            {{name}}<!--拿到name就可以显示-->
        </li>
    </lu>
  
    <!--template 可以省略一些不必要的dom元素-->
    <template v-for="(user,index) in person">
         <!--index是下标,user是person的元素,person是vue中的数组-->
        {{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对象中的数组names,name是我们自己定义的一个变量.
  • v-for="(user,index) in person",其中personvue对象中的数组person,userperson中的对象元素,index是对象元素的下标.
  • "(value,key) in user",valuekeyuser里面的valuekey,通过这种方式可以拿到对应需要的value或者key
  • template可以帮我们省略一些不必要的dom元素,例如我一个块只用<span>就可以解决问题的,但是我多套了一层<div>,这个时候template就可以帮我们省略掉这个<div>了.

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务