最近发现我们可以使用v-for进行解构。
之所以起作用,是因为 Vue 将v-for的整个第一部分直接提升到函数的参数部分:
<li v-for="____ in array">
</li>
function (____) {
//...
}
- 1.
- 2.
- 3.
- 4.
- 5.
然后,Vue 在内部使用此函数来渲染列表。
这说明可以放在函数中括号中的任何有效Javascript也可以放在v-for中,如下所示:
<li v-for="{
// Set a default
radius = 20,
// Destructure nested objects
point: { x, y },
} in circles">
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
其他 v-for 技巧
众所周知,可以通过使用如下元组从v-for中获取索引:
当使用一个对象时,你也可以捕获 key:
<li v-for="(value, key) in {
name: 'Lion King',
released: 2019,
director: 'Jon Favreau',
}">
{{ key }}: {{ value }}
</li>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
还可以将这两种方法结合使用,获取属性的键和索引:
<li v-for="(value, key, index) in {
name: 'Lion King',
released: 2019,
director: 'Jon Favreau',
}">
#{{ index + 1 }}. {{ key }}: {{ value }}
</li>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
Vue 确实支持对 Map 和Set对象进行迭代,但是由于它们在 Vue 2.x 中不具有响应性,因此其用途非常有限。 我们还可以在此处使用任何 Iterable,包括生成器。
顺便说一句,我有时使用Map或Set,但通常仅作为中间对象来进行计算。 例如,如果我需要在列表中查找所有唯一的字符串,则可以这样做:
computed() {
uniqueItems() {
// 从数组创建一个Set,删除所有重复项
const unique = new Set(this.items);
// 将该 Set 转换回可用于 Vue 的数组
return Array.from(unique);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
字符串和 v-for
你知道吗,还可以使用v-for遍历字符串?
文档中没有这一点,我只是在通读代码以弄清楚v-for是如何实现的时候才发现了它:
<p v-for="character in 'Hello, World'">
{{ character }}
</p>
- 1.
- 2.
- 3.
上面会打印每个字符。
作者:Michael Thiessen 译者:前端小智 来源:medium
原文:https://forum.vuejs.org/t/destructuring-rest-parameter/23332
本文转载自微信公众号「 大迁世界」,可以通过以下二维码关注。转载本文请联系前端小智公众号。