很多人不知道 V-for 可以這樣解構(gòu)
最近發(fā)現(xiàn)我們可以使用v-for進(jìn)行解構(gòu)。
之所以起作用,是因為 Vue 將v-for的整個第一部分直接提升到函數(shù)的參數(shù)部分:
- <li v-for="____ in array">
- </li>
- function (____) {
- //...
- }
然后,Vue 在內(nèi)部使用此函數(shù)來渲染列表。
這說明可以放在函數(shù)中括號中的任何有效Javascript也可以放在v-for中,如下所示:
- <li v-for="{
- // Set a default
- radius = 20,
- // Destructure nested objects
- point: { x, y },
- } in circles">
其他 v-for 技巧
眾所周知,可以通過使用如下元組從v-for中獲取索引:
當(dāng)使用一個對象時,你也可以捕獲 key:
- <li v-for="(value, key) in {
- name: 'Lion King',
- released: 2019,
- director: 'Jon Favreau',
- }">
- {{ key }}: {{ value }}
- </li>
還可以將這兩種方法結(jié)合使用,獲取屬性的鍵和索引:
- <li v-for="(value, key, index) in {
- name: 'Lion King',
- released: 2019,
- director: 'Jon Favreau',
- }">
- #{{ index + 1 }}. {{ key }}: {{ value }}
- </li>
Vue 確實支持對 Map 和Set對象進(jìn)行迭代,但是由于它們在 Vue 2.x 中不具有響應(yīng)性,因此其用途非常有限。 我們還可以在此處使用任何 Iterable,包括生成器。
順便說一句,我有時使用Map或Set,但通常僅作為中間對象來進(jìn)行計算。 例如,如果我需要在列表中查找所有唯一的字符串,則可以這樣做:
- computed() {
- uniqueItems() {
- // 從數(shù)組創(chuàng)建一個Set,刪除所有重復(fù)項
- const unique = new Set(this.items);
- // 將該 Set 轉(zhuǎn)換回可用于 Vue 的數(shù)組
- return Array.from(unique);
- }
- }
字符串和 v-for
你知道嗎,還可以使用v-for遍歷字符串?
文檔中沒有這一點,我只是在通讀代碼以弄清楚v-for是如何實現(xiàn)的時候才發(fā)現(xiàn)了它:
- <p v-for="character in 'Hello, World'">
- {{ character }}
- </p>
上面會打印每個字符。
作者:Michael Thiessen 譯者:前端小智 來源:medium
原文:https://forum.vuejs.org/t/destructuring-rest-parameter/23332
本文轉(zhuǎn)載自微信公眾號「 大遷世界」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系前端小智公眾號。