回到部落格

2024-01-10

【React-Vue】List Rendering with Vue.js

【React-Vue】List Rendering with Vue.js

原文發表於 Medium

之前我們討論過React的List Rendering,有Vue的愛用者會對React用戶表示:「這也太不優雅了吧!!!」今天我們就來看看Vue.js怎麼渲染一串資料。(有關React的List Rendering,參考:【React 新手村】如何簡單快速渲染一串資料在頁面上?

先預告,這篇文章會很短,因為Vue的語法真的也很簡潔。

首先,假設我有一串客戶的資料,每筆內含姓名、電話與email,大概如下方的Array內容所示:

<script setup> const customerList = [ { name: 'John Doe', email: 'john.doe@example.com', phone: '(555) 123-4567' }, { name: 'Jane Smith', email: 'jane.smith@example.com', phone: '(555) 987-6543' }, { name: 'Robert Johnson', email: 'robert.johnson@example.com', phone: '(555) 567-8901' }, { name: 'Emily Davis', email: 'emily.davis@example.com', phone: '(555) 234-5678' }, { name: 'Michael Lee', email: 'michael.lee@example.com', phone: '(555) 876-5432' } ]; </script>

若想要照搬React使用map方法來逐筆渲染的話,是做不到的,下面是錯誤的程式碼寫法:

<template>
  <main>  
  
    //在Vue的程式碼內,千.萬.不.要.這.樣.做!!!  
  
    {{   
    customerList.map((customer)=> {return(  
     <div>   
      <h1> customer.name  </h1>  
      <p> customer.phone </p>  
      <p> customer.email </p>  
    </div>  
    )})  
      
    }}  
  
  </main>  
  
</template>

那麼正確的寫法是啥呢?

v-for:一個神奇的attribute

Vue有個內建的功能:v-for,它是在template中個元素之間可以加入的一個attribute。從名字可以猜到,它代表的就是一個for loop操作,Vue透過它來進行List Rendering。

說到for loop,記得我第一次接觸程式語言時,for loop的威力讓我大為驚嘆,好像學了之後就已經可以被稱作『工程師』了(?)。v-for的操作是for loop 的一種 :[for in loop](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in>) ,我們先來複習一下JavaScript的[for in loop](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in>) 怎麼玩:

//資料來源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
const object = { a: 1, b: 2, c: 3 };

for (const property in object) {  
  console.log(`${property}: ${object[property]}`);  
}  
  
// Expected output:  
// "a: 1"  
// "b: 2"  
// "c: 3"

綜上,for in loop就是針對一串資料逐一做些操作,跟map的功能是有那麼點像的。

回歸主題,我們來看看v-for如何使用:

<template>
  <main>  
      
    <!--V-for的用法-->  
    <div v-for="customer in customerList">   
      <h1>{{ customer.name  }}</h1>  
      <p>{{ customer.phone }}</p>  
      <p>{{ customer.email }}</p>  
  
    </div>  
  
  </main>  
  
</template>

因此相對於React來說,Vue直接把語法利用框架內包起來了,因此在視覺感受上非常的乾淨俐落。

但不得不說,本該在for()裏面的那段customer in customerList,這裡要用字串的形式寫出來,然後又寫在attribute上,這個轉折還真的需要想一下。

在Vue的專案內,非常容易看到在組件中間有v-linkv-for等等v開頭的attribute,都是Vue的專屬功能。

在Vue的專案內,非常容易看到在組件中間有v-linkv-for等等v開頭的attribute,都是Vue的專屬功能。

以上簡短說明Vue.js的List Rendering 。綜觀下來,其實與React的map方法異曲同工,也代表在需要渲染大量資料時,無論何種前端框架幾乎都能提供簡便快速的方法。

最後祝大家天天有coding,天天有成長。我是一個半路出家卻把coding當作興趣,且不斷鑽研技巧的開發者,希望有朝一日能成為全然獨當一面的技術大神。