AdSense

網頁

2026/1/6

Vue Nuxt 3 useFetch 多查詢參數

本篇介紹Vue Nuxt 3的useFetch呼叫API時帶入頁面輸入的多個參數。


事前要求

參考「Vue Nuxt 3 同步網址列查詢參數」。


修改server/api/orders.get.js

修改API端使用getQuery接收頁面傳來的查詢參數statuscountry,並新增訂單資料orders的屬性country以作為篩選條件。

調整篩選訂單資料的邏輯,除了status外,也加入對country的篩選。

server/api/orders.get.js

export default defineEventHandler(async (event) => {
  const { status, country } = getQuery(event); // 取得查詢參數

  await new Promise((r) => setTimeout(r, 2000)); // 模擬延遲

  const orders = [
    { id: 10001, status: "pending", country: "US" },
    { id: 10002, status: "done", country: "JP" },
    { id: 10003, status: "pending", country: "CN" },
    { id: 10004, status: "done", country: "KR" },
    { id: 10005, status: "pending", country: "VN" },
    { id: 10006, status: "done", country: "US" },
    { id: 10007, status: "pending", country: "JP" },
  ];

  let result = orders;

  // 根據查詢參數篩選訂單
  if (status) {
    result = result.filter((o) => o.status === status);
  }

  if (country) {
    result = result.filter((o) => o.country === country);
  }
  return result;
});


修改pages/home/export/index.vue

修改頁面,新增出口國家的下拉選單<select v-model="country">,並在點擊查詢按鈕後調用search(),將查詢參數同步到網址列,帶入useFetch的API查詢參數,顯示訂單的國家代碼。

pages/home/export/index.vue

<template>
  <div>
    <h1>出口業務</h1>

    <label>
      訂單狀態:
      <input v-model="status" placeholder="pending/done">
    </label>
    <br>
    <label>
      出口國家:
      <select v-model="country">
        <option value="">全部國家</option>
        <option value="US">美國(US)</option>
        <option value="JP">日本(JP)</option>
        <option value="CN">中國(CN)</option>
        <option value="KR">韓國(KR)</option>
        <option value="VN">越南(VN)</option>
      </select>
    </label>
    <br>

    <button @click="search">查詢</button>

    <!--省略-->
    
    <ul v-else>
      <li v-for="order in orders" :key="order.id">
        <NuxtLink :to="`/home/export/${order.id}`">
          訂單 #{{ order.id }}, 狀態: {{ order.status }}, 出口國家:{{ order.country }}
        </NuxtLink>
      </li>
    </ul>

  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const status = ref(route.query.status || '')
const queryStatus = ref(route.query.status || '')
const country = ref(route.query.country || '')
const queryCountry = ref(route.query.country || '')

const { data: orders, pending, error, refresh } = useFetch('/api/orders', {
  query: {
    status: queryStatus,
    country: queryCountry,
  },
  default: () => [],
})

function search() {
  queryStatus.value = status.value
  queryCountry.value = country.value

  router.push({
    query: {
      status: status.value || undefined,
      country: country.value || undefined,
    },
  })

  refresh()
}
</script>

<style scoped>
.error {
  color: red;
}
</style>

github


查詢效果如下:



接著可以把寫死的下拉選單內容抽出改由後端API取得

沒有留言:

AdSense