Vue.js学习笔记:v-for循环

来源:互联网 发布:淘宝如何上传3c认证 编辑:程序博客网 时间:2024/06/05 00:38

    v-for标签可以用来遍历数组,将数组的每一个值绑定到相应的视图元素中去,此外,v-for还可以遍历对象的属性,并且可以和template模板元素一起使用。


一.基本语法

(1).v-for基于一个数组渲染一个列表

 语法:item in items(数组元素的别名 in 数据数组)


我们可以使用 v-for 指令,将一个数组渲染为列表项。v-for 指令需要限定格式为 item in items 的特殊语法,其中,items 是原始数据数组(source data array),而 item 是数组中每个迭代元素的指代别名(alias)

<!DOCTYPE html><html><head><meta charset="utf-8"><title>pejeco</title></head><div id="didi-navigator">    <ul>        <li v-for="item in items">            {{ item.text }}        </li>    </ul></div><script src="js/vue.js"></script><script type="text/javascript">var vm =new Vue({        el: '#didi-navigator',        data: {            items: [                { text: '巴士' },                { text: '快车' },                { text: '专车' },                { text: '顺风车' },                { text: '出租车' },                { text: '代驾' }            ]        }    })</script></body></html>



(2).template v-for

渲染一个包含多个元素的块,需要将多个标签都用v-for遍历,那么就需要用template标签。同样,template在实际渲染的时候不会出现,只是起到一个包裹作用。

<div id="didi-navigator">    <ul>    <template v-for="tab in tabs">        <li>cart is {{ tab }}</li>    </template>    </ul></div>




二.迭代语法变化
  由于
在Vue2.0中,v-for迭代语法已经发生了变化:

  • 丢弃$index$key

  • 新数组语法

    • value in arr

    • (value, index) in arr

  • 新对象语法

    • value in obj

    • (value, key) in obj

    • (value, key, index) in obj

(1).index索引

在 v-for 块内我们能完全访问父组件作用域内的属性,另有一个特殊变量 index,正如你猜到的,它是当前数组元素的索引。

<!DOCTYPE html><html><head><meta charset="utf-8"><title>pejeco</title></head><div id="example-2"><h1>{{ fruits}}</h1><ul><li v-for="(item,index) in items">  {{ index }}: {{ item.message }}</li></ul></div><script src="js/vue.js"></script><script type="text/javascript">var example2 = new Vue({el: '#example-2',data: {fruits: '水果',items: [{ message: '苹果' },{ message: '凤梨' },{ message: '香蕉' }]}})</script></body></html>



你还可以不使用 in,而是使用 of 作为分隔符,因为它更加接近 JavaScript 迭代器语法:

<div id="example-2"><h1>{{ fruits}}</h1><ul><li v-for="(item,index) of items">  {{ index }}{{ item.message }}</li></ul></div>

也是如上图所示。


(2).key键名

语法:(value, key) in obj

<!DOCTYPE html><html><head><meta charset="utf-8"><title>pejeco</title></head><div id="example-2"><h1>{{ fruits}}</h1><ul><li v-for="(value, key) in items">  {{ key }}: {{ value }}</li></ul></div><script src="js/vue.js"></script><script type="text/javascript">var example2 = new Vue({el: '#example-2',data: {fruits: '水果',items:{a: '苹果' ,b: '凤梨',c: '香蕉'}}})</script></body></html>



语法:(value, key, index) in obj



简单分析下,更多的内容查看官网:https://vuefe.cn/v2/guide/list.html


原创粉丝点击