說明在 Vue 製作點擊列表標頭調整排序的做法。

功能 實作方式
表格資料 使用 ref() 儲存原始資料
排序欄位 sortKey 儲存目前排序欄位
升冪/降冪 sortAsc 控制排序方向
排序邏輯 用 computed() 建立排序後的陣列

 

HTML 部分

<template>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th @click="sortBy('name')">
          姓名
          <span v-if="sortKey === 'name'">
            <i :class="sortAsc ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
          </span>
        </th>
        <th @click="sortBy('email')">
          Email
          <span v-if="sortKey === 'email'">
            <i :class="sortAsc ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
          </span>
        </th>
        <th @click="sortBy('height')">
          身高
          <span v-if="sortKey === 'height'">
            <i :class="sortAsc ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
          </span>
        </th>
        <th @click="sortBy('weight')">
          體重
          <span v-if="sortKey === 'weight'">
            <i :class="sortAsc ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(person, index) in sortedPeople" :key="index">
        <td>{{ person.name }}</td>
        <td>{{ person.email }}</td>
        <td>{{ person.height }}</td>
        <td>{{ person.weight }}</td>
      </tr>
    </tbody>
  </table>
</template>

 

<script setup> 排序邏輯

import { ref, computed } from 'vue'

// 假資料:姓名、email、身高(cm)、體重(kg)
const people = ref([
  { name: '王小明', email: '[email protected]', height: 172, weight: 68 },
  { name: '陳美麗', email: '[email protected]', height: 160, weight: 54 },
  { name: '李志強', email: '[email protected]', height: 180, weight: 75 },
  { name: '張惠君', email: '[email protected]', height: 165, weight: 60 }
])

const sortKey = ref('')
const sortAsc = ref(true)

// 切換排序欄位
const sortBy = (key) => {
  if (sortKey.value === key) {
    sortAsc.value = !sortAsc.value
  } else {
    sortKey.value = key
    sortAsc.value = true
  }
}

// 排序後的資料
const sortedPeople = computed(() => {
  const list = [...people.value]
  if (!sortKey.value) return list

  return list.sort((a, b) => {
    const valA = a[sortKey.value]
    const valB = b[sortKey.value]

    if (valA < valB) return sortAsc.value ? -1 : 1
    if (valA > valB) return sortAsc.value ? 1 : -1
    return 0
  })
})

 

這樣就可以點擊列表的標頭去做資料內容排序,如果不是用表格,只要在對應的地方觸發 method 就好了。