iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Vue.js

Vue.js 新手入門之路系列 第 16

Vue.js 新手入門之路 - Watchers (二)

  • 分享至 

  • xImage
  •  

今天要繼續來學習有關 watcher 的用法

一次性的監聽器

加上 once: true 之後 watch 便只會觸發一次

<script setup>
import { ref, watch } from 'vue'

const source = ref(0)
const attr = 'box'

watch(source, (newValue, oldValue) => {
  console.log('source 改變了:', oldValue, '→', newValue)
}, { once: true })

function change() {
  source.value++
}
</script>

<template>
  <div :class="attr">
    <p>source: {{ source }}</p>
    <button @click="change">改變 source</button>
  </div>
</template>

<style scoped>
    .box{
        gap: 5px;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: x-large;
        border: solid;
        margin-left: 650px;
        margin-top: 5px;
        height: 300px;
        width:350px;
        padding: 35px;
    }
</style>

https://ithelp.ithome.com.tw/upload/images/20250905/20178296TdOlL44mMe.png

觸發時機

我們可以自由選擇 watchers 的觸發時機,使用方式 flush:'時機'
分為以下

  • flush: 'pre'
  • flush: 'post'
  • flush: 'sync'
flush 選項 觸發時機 特點 適合用於
pre (預設) DOM 更新前 回調會被批次處理,效能最佳 一般情況
post DOM 更新後 可以安全存取最新 DOM 需要讀取更新後的 DOM
sync 狀態一變就馬上執行 沒有批次處理,可能觸發很多次 監聽簡單布林值

用 Vue2 的方式寫可以使用 this.watch

<script>
export default {
  data() {
    return {
      question: ''
    }
  },
  created() {
    const unwatch = this.$watch('question', (newQuestion) => {
      console.log('question 改變:', newQuestion)
    })

    setTimeout(() => {
      unwatch()
      console.log('已停止監聽 question')
    }, 5000)
  }
}
</script>

<template>
  <div class="box">
    <p>請輸入問題:</p>
    <input v-model="question" placeholder="輸入文字" />
    <p>目前 question: {{ question }}</p>
  </div>
</template>

<style scoped>
.box {
  border: 1px solid #333;
  padding: 20px;
  width: 300px;
  margin: 20px auto;
  font-size: 18px;
}
</style>


<style scoped>
    .box{
        gap: 5px;
        text-align: center;
        display: flex;
        flex-direction: column;
        justify-content: center;
        font-size: x-large;
        border: solid;
        margin-left: 650px;
        margin-top: 5px;
        height: 300px;
        width:350px;
        padding: 35px;
    }
</style>

而使用 watch$watch() 方法宣告的監聽器,可以使用 unwatch() 停止其繼續監聽,這邊設定監聽五秒後執行 unwatch() 所以不再印出 question 的變動
https://ithelp.ithome.com.tw/upload/images/20250905/20178296efVOsEk0ew.png

ref:
https://zh-hk.vuejs.org/guide/essentials/watchers.html


上一篇
Vue.js 新手入門之路 - Watchers
下一篇
Vue.js 新手入門之路 - 元件化
系列文
Vue.js 新手入門之路17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言