很多人不知道 V-for 可以這樣解構
最近發現我們可以使用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中獲取索引:
當使用一個對象時,你也可以捕獲 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
本文轉載自微信公眾號「 大遷世界」,可以通過以下二維碼關注。轉載本文請聯系前端小智公眾號。