Vue v-for 指令
实例
使用 v-for 指令基于数组创建动物列表:
<template><h2>v-for 指令实例</h2><p>使用 v-for 指令基于数组创建动物列表。</p><ul><li v-for="x in animals">{{ x }}</li></ul></template>
定义与用法
v-for 指令用于基于数据源呈现多个元素。
v-for 指令与语法 "(item, key, index) in dataSource" 一起使用,其中
- "item" 别名表示 "dataSource" 中的一个元素。
- "key" 别名表示如果 "dataSource" 数据源是对象,则可用于获取属性名称。
- 如果数据源是数组或对象,则可以使用 "index" 别名。
- "dataSource" 必须是您正在循环使用的实际数据源的名称。
您可以自己选择 "item", "key" 和 "index" 别名的名称,但顺序是 "item, key, index"。
这些是 v-for 指令可以使用的数据源:
| 数据源类型 | 详情 |
|---|---|
| Array | v-for 循环遍历数组,可以提取并使用每个元素的元素和索引。 |
| Object | v-for 循环通过对象属性名称、值和索引可以挑选出来使用。 |
| number | v-for 呈现一个列表,其中每个项目都是一个数字,最后一个数字是提供的数字每个元素的索引也可以被挑选出来。 |
| string | v-for 在字符串中循环每个字符及其索引都可以挑选出来使用。 |
| Iterable | v-for 还可以循环遍历可迭代项 Iterable 是使用 Iterable 协议的值,如 Map 和 Set。 |
注意:为了优化性能,Vue 在处理数据源时重用使用
v-for 创建的元素。为了防止 Vue 在使用 v-for 时错误地重用元素,您应该始终使用带有 v-bind 的特殊键属性,以唯一地标记每个元素。更多实例
实例 1
使用 v-for 指令基于数组呈现动物列表,并取数组中每个元素的索引:
<template><h2>v-for 指令实例</h2><p>使用 v-for 指令基于数组创建动物列表和每种动物的索引。</p><ul><li v-for="(x, index) in animals">On index {{ index }}: "{{ x }}"</li></ul></template><script>export default {data() {return {animals: ['Tiger','Zebra','Wolf','Crocodile','Seal']};}};</script>
实例 2
使用 v-for 指令来呈现属性列表,为对象中的每个属性挑选属性名称和值:
<template><h2>v-for 指令实例</h2><p>对对象使用 v-for 指令来创建对象属性和相应属性值的列表。</p><ul><li v-for="(x, key) in animal">(Property name: value) = ({{ key }}: {{ x }})</li></ul></template><script>export default {data() {return {animal: {name: 'Lion',heightCM: 110,weightKG: 150}};}};</script>
实例 3
使用 v-for 指令来呈现基于数字的列表:
<template><h2>v-for 指令实例</h2><p>使用带有 number 的 v-for 指令来呈现具有该数量元素的列表。</p><ul><li v-for="(x, index) in 10">Item: {{ x }}, index: {{ index }}</li></ul></template>
实例 4
使用 v-for 指令在字符串中循环:
<template><h2>v-for 指令实例</h2><p>使用 v-for 指令循环遍历字符串中的字符。</p><ul><li v-for="(x, index) in 'Ice cream'">Item: "{{ x }}", index: {{ index }}</li></ul></template>
实例 5
使用 v-for 指令循环通过使用 Iterable 协议创建的对象:
<template><h2>v-for 指令实例</h2><p>基于使用 Iterable Protocol 创建的对象,使用 v-for 指令来呈现列表。</p><ul><li v-for="value in iterableObject">{{ value }}</li></ul></template><script>export default {data() {return {iterableObject: this.createIterable(['City', 'Park', 'River'])};},methods: {createIterable(array) {let currentIndex = -1;return {[Symbol.iterator]: function () {return {next: () => {if (currentIndex < array.length - 1) {currentIndex++;return { value: array[currentIndex], done: false };} else {return { done: true };}}};}};}}};</script>
实例 6
使用 v-for 指令为字符串中的每个字符呈现一个 div 元素。始终建议您将 v-bind:key 与 v-for 指令一起使用:
<template><h2>v-for 指令实例</h2><p>将v-for指令与 'v-bind:key' 一起使用以基于字符串呈现 DIV 元素。</p><div id="wrapper"><div v-for="x in text" v-bind:key="x">{{ x }}</div></div></template><script>export default {data() {return {text: 'I love ice cream.'};}};</script><style>#wrapper {display: flex;flex-wrap: wrap;width: 280px;}#wrapper > div {margin: 5px;padding: 5px 10px;border: solid black 1px;background-color: lightgreen;}</style>