在Vue3中,computed
、watch
和watchEffect
是三個非常重要的響應式API,它們可以幫助我們更好地管理和響應數據的變化。本文將詳細介紹這三個API的使用方法和區別。
computed
用于創建一個計算屬性,它會根據依賴的響應式數據自動更新。計算屬性是基于它們的依賴進行緩存的,只有在依賴發生變化時才會重新計算。
import { ref, computed } from 'vue';
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
console.log(doubleCount.value); // 0
count.value = 1;
console.log(doubleCount.value); // 2
計算屬性默認是只讀的,但你可以通過提供一個setter來使其可寫。
const count = ref(0);
const doubleCount = computed({
get: () => count.value * 2,
set: (newValue) => {
count.value = newValue / 2;
}
});
doubleCount.value = 4;
console.log(count.value); // 2
watch
用于監聽一個或多個響應式數據的變化,并在變化時執行回調函數。watch
可以監聽ref
、reactive
對象、計算屬性等。
import { ref, watch } from 'vue';
const count = ref(0);
watch(count, (newValue, oldValue) => {
console.log(`count changed from ${oldValue} to ${newValue}`);
});
count.value = 1; // 輸出: count changed from 0 to 1
你可以通過傳遞一個數組來監聽多個數據源。
const count1 = ref(0);
const count2 = ref(0);
watch([count1, count2], ([newCount1, newCount2], [oldCount1, oldCount2]) => {
console.log(`count1 changed from ${oldCount1} to ${newCount1}`);
console.log(`count2 changed from ${oldCount2} to ${newCount2}`);
});
count1.value = 1; // 輸出: count1 changed from 0 to 1
count2.value = 2; // 輸出: count2 changed from 0 to 2
默認情況下,watch
是淺層監聽的,如果你需要監聽對象內部的變化,可以使用deep
選項。
const state = reactive({ count: 0 });
watch(
() => state,
(newValue, oldValue) => {
console.log('state changed', newValue);
},
{ deep: true }
);
state.count = 1; // 輸出: state changed { count: 1 }
watchEffect
是一個立即執行的監聽器,它會自動追蹤其內部使用的響應式數據,并在這些數據變化時重新執行。
import { ref, watchEffect } from 'vue';
const count = ref(0);
watchEffect(() => {
console.log(`count is ${count.value}`);
});
count.value = 1; // 輸出: count is 1
watchEffect
返回一個停止監聽的函數,你可以在需要時調用它來停止監聽。
const stop = watchEffect(() => {
console.log(`count is ${count.value}`);
});
count.value = 1; // 輸出: count is 1
stop();
count.value = 2; // 不會輸出
watchEffect
的回調函數可以接收一個onInvalidate
函數,用于清理副作用。
watchEffect((onInvalidate) => {
const timer = setTimeout(() => {
console.log(`count is ${count.value}`);
}, 1000);
onInvalidate(() => {
clearTimeout(timer);
});
});
count.value = 1; // 1秒后輸出: count is 1
count.value = 2; // 1秒后輸出: count is 2
computed
:用于創建計算屬性,適合處理依賴其他數據的派生數據。watch
:用于監聽數據的變化,適合在數據變化時執行復雜的邏輯。watchEffect
:自動追蹤依賴并立即執行,適合處理不需要顯式指定依賴的場景。根據不同的需求,選擇合適的API可以幫助你更高效地管理Vue應用中的響應式數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。