2

很多人不知道 v-for 可以这样解构!

 2 years ago
source link: https://www.fly63.com/article/detial/11308
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
更新日期: 2022-03-31阅读量: 60标签: 循环分享

扫一扫分享

最近发现我们可以使用v-for进行解构。

之所以起作用,是因为 vue 将v-for的整个第一部分直接提升到函数的参数部分:

<li v-for="____ in array">
</li>
function (____) {
  //...
}

然后,Vue 在内部使用此函数来渲染列表。

这说明可以放在函数中括号中的任何有效Javascript也可以放在v-for中,如下所示:

<li v-for="{
  // Set a default
  radius = 20,

  // Destructure nested objects
  point: { x, y },
} in circles">

你可以在这里为非作歹,只是不要太疯狂。

其他 v-for 技巧

众所周知,可以通过使用如下元组从v-for中获取索引:

<li v-for="(movie, index) in [
  'Lion King',
  'Frozen',
  'The Princess Bride'
]">
  {{ index + 1 }} - {{ movie }}
</li>

当使用一个对象时,你也可以捕获 key:

<li v-for="(value, key) in {
  name: 'Lion King',
  released: 2019,
  director: 'Jon Favreau',
}">
  {{ key }}: {{ value }}
</li>

还可以将这两种方法结合使用,获取属性的键和索引:

<li v-for="(value, key, index) in {
  name: 'Lion King',
  released: 2019,
  director: 'Jon Favreau',
}">
  #{{ index + 1 }}. {{ key }}: {{ value }}
</li>

Vue 确实支持对 Map 和Set对象进行迭代,但是由于它们在 Vue 2.x 中不具有响应性,因此其用途非常有限。 我们还可以在此处使用任何 Iterable,包括生成器。

顺便说一句,我有时使用Map或Set,但通常仅作为中间对象来进行计算。 例如,如果我需要在列表中查找所有唯一的字符串,则可以这样做:

computed() {
  uniqueItems() {
    // 从数组创建一个Set,删除所有重复项
    const unique = new Set(this.items);

    // 将该 Set 转换回可用于 Vue 的数组
    return Array.from(unique);
  }
}

字符串和 v-for

你知道吗,还可以使用v-for遍历字符串?

文档中没有这一点,我只是在通读代码以弄清楚v-for是如何实现的时候才发现了它:

<p v-for="character in 'Hello, World'">
  {{ character }}
</p>

上面会打印每个字符。

作者:Michael Thiessen  译者:前端小智 来源:medium
原文:https://forum.vuejs.org/t/destructuring-rest-parameter/23332

链接: https://www.fly63.com/article/detial/11308


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK