結論
watch
関数から返されるハンドル関数を使用する(watchEffect
も同様)1。
const unwatch = watch(something, () => {
// 実行したい処理
unwatch() // ウォッチャーの停止
})
デモ
<script setup>
import { ref, reactive, watch } from 'vue'
const counter = ref(0)
const watcher = reactive({ normal: 0, once: 0 })
// normal watch
watch(counter, () => {
watcher.normal++
})
// watch only once
const unwatch = watch(counter, () => {
watcher.once++
unwatch()
})
</script>
<template>
<div v-for="(value, key) in watcher" :key="key">
{{ key }} watcher: {{ value }}
</div>
<button @click="counter++">{{ counter }}</button>
</template>
ボタンをクリックするたびにcounter
がインクリメントされます。normal
とonce
は両方ともcounter
を監視しますが、once
は1回目の変更検知時にunwatch()
でウォッチャーを停止しているので、2回目以降の変更は検知しません。