Appearance
響應性狀態觀察者
Vue 中,除了在 <template> 區塊中使用響應性狀態來更新 UI 外,我們也可能需要在程式邏輯中追蹤響應性狀態的變化:
- 在響應性狀態變化時執行一些動作。
- 根據響應性狀態的值來計算出另一個響應性狀態。
watch/watchEffect
watch()在響應性狀態變化時執行一些動作:watchEffect()使用跟蹤的狀態進行其他操作時使用,跟蹤執行函式內所有響應性狀態,要注意效能問題。
Computed
js
import { ref, computed } from 'vue'
export default {
setup() {
const height = ref(1.7) // 身高(公尺)
const weight = ref(60) // 體重(公斤)
const bmi = computed(() => {
return (weight.value / (height.value * height.value)).toFixed(2)
})
return { height, weight, bmi }
}
}import { ref, computed } from 'vue'
export default {
setup() {
const height = ref(1.7) // 身高(公尺)
const weight = ref(60) // 體重(公斤)
const bmi = computed(() => {
return (weight.value / (height.value * height.value)).toFixed(2)
})
return { height, weight, bmi }
}
}Reactivity 關係圖

Summary
computed:根據響應性狀態產生另一個響應性狀態,可另外定義setter。watch/watchEffect:監聽響應性狀態變化執行相對應的行為。watch明確指定跟蹤對象;watchEffect跟蹤執行函式內所有響應性狀態。watch對象可以是響應性狀態、包含響應性狀態的getter。
- 使用 handle function 停止跟蹤。