👁️

Vue 3で一度だけwatchする方法

2023/03/24に公開

結論

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がインクリメントされます。normalonceは両方ともcounterを監視しますが、onceは1回目の変更検知時にunwatch()でウォッチャーを停止しているので、2回目以降の変更は検知しません。

脚注
  1. ウォッチャーの停止 ↩︎

Discussion