點燈坊

失くすものさえない今が強くなるチャンスよ

使用 watch() 追蹤多個 State 呼叫 API

Sam Xiao's Avatar 2024-02-06

除了 watchEffect() 能同時追蹤多個 State 外,事實上 watch() 也能同時追蹤 State。

Version

Vue 3.4

watch()

<template>
  <div>Limit: <input v-model.number="limit" /></div>
  <div>Skip: <input v-model.number="skip" /></div>
  <ul>
    <li v-for="(item, i) in products" :key="i">
      <span>{{ item.title }}</span>
      <span>,</span>
      <span>{{ item.price }}</span>
    </li>
  </ul>
</template>
<script setup>
import { ref, watch } from 'vue'

let skip = ref(10)
let limit = ref(10)
let products = ref([])

watch(
  [skip, limit],
  async () => {
    try {
      let res = await fetch(`https://dummyjson.com/products?limit=${limit.value}&skip=${skip.value}`)
      let data = await res.json()
      products.value = data.products
    } catch (e) {
      console.err(e)
    }
  },
  { immediate: true }
)
</script>

Line 2

<div>Limit: <input v-model.number="limit" /></div>
<div>Skip: <input v-model.number="skip" /></div>
  • User 可輸入 limitskip state

Line 4

<ul>
  <li v-for="(item, i) in products" :key="i">
    <span>{{ item.title }}</span>
    <span>,</span>
    <span>{{ item.price }}</span>
  </li>
</ul>
  • v-for:列舉 products state

Line 15

let skip = ref(10)
let limit = ref(10)
let products = ref([])
  • skip state:儲存 skip 筆數
  • limit state:儲存 回傳 筆數
  • products state:儲存 API 回傳資料

Line 19

watch(
  [skip, limit],
  async () => {}
)
  • watch():追蹤 skiplimit state,當要追蹤多個 state 時,傳入 Array 即可

Conclusion

  • 若要 Watch 同時追蹤多個 State,只能使用 Composition API 的 watch(),Options API 無法同時多個 State