iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Vue.js

從零開始的Vue之旅系列 第 11

語法介紹Part4-watch

  • 分享至 

  • xImage
  •  

今天來認識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' 導入watch
const count = ref(0) 建立響應式變數count,初值為0
const message = ref('Hello') 建立響應式字串message
watch([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

  • 觀察資料並執行程式碼
  • 觸發時機:被監聽的ref或reactive改變時
  • 沒有快取,每次變化都會執行

computed

  • 基於現有資料產生新值
  • 觸發時機 : 依賴的變數改變時
  • 有快取,依賴的變數不便就不會從新計算

總結來說就是當要執行「在變化時做事」用watch,而要執行「計算新值」時則用computed。


今天先學習到這裡,各位明天見~


上一篇
語法介紹Part3-Lifecycle Hooks&模板參考
系列文
從零開始的Vue之旅11
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言