LoginSignup
0
0

More than 1 year has passed since last update.

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

Posted at

結論

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. ウォッチャーの停止

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0