今天來認識watch
watch : 監聽資料變化並執行特定動作的工具,當某個資料改變時,則自動觸發對應的程式。
語法範例
watch( 監聽目標, ( 改變後的值, 改變前的值 ) => {
console.log(`count 從 ${改變前的值} 變成 ${改變後的值}`)
})
可一次監聽多個來源(ref)
範例
watch([count, message], ([newCount, newMessage], [oldCount, oldMessage]) => {
console.log(`count: ${oldCount} → ${newCount}`)
console.log(`message: ${oldMessage} → ${newMessage}`)
})
參數為陣列,第一個參數為陣列[count, message],同時間聽count和messagexu兩個響應式變數,其中任一值有變動時,回乎函式都會執行。
範例
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const message = ref('Hello')
watch([count, message], ([newCount, newMessage], [oldCount, oldMessage]) => {
console.log(`count: ${oldCount} → ${newCount}`)
console.log(`message: ${oldMessage} → ${newMessage}`)
})
function update() { //建立方法update
count.value++
message.value = message.value + '!'
}
</script>
<template>
<p>{{ message }} ({{ count }})</p>
<button @click="update">更新</button>
</template>
import { ref, watch } from 'vue'
導入watchconst count = ref(0)
建立響應式變數count,初值為0const message = ref('Hello')
建立響應式字串messagewatch([count, message], ([newCount, newMessage], [oldCount, oldMessage]) => {.....})
同時監聽count和message,回呼第一個參數[newCount, newMessage]
,和第二個參數 [oldCount, oldMessage]
,在回呼時印出新舊值,方便偵錯或做副作用<p>{{ message }} ({{ count }})</p>
顯示目前收到的count和message<button @click="update">更新</button>
點擊按鈕時呼叫update(), 觸發count和message狀態改變。意思就是每按一次按鈕,count值就會加1,message後面就會多一個 !
watch 和computed容易互相混淆。這裡簡單整理兩者差異
watch
computed
總結來說就是當要執行「在變化時做事」用watch,而要執行「計算新值」時則用computed。
今天先學習到這裡,各位明天見~