13
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue3のwatcherでpropsの値の変更を監視する【備忘録】

Posted at

propsで値を渡した場合、refdataで受け取っても変更を監視することはできません。
監視するにはwatchの使い方を工夫する必要があります。

参照元

公式ドキュメントの監視ソースの種類に書かれた、getterを使います。

Vue3+setup(+TypeScript)の場合

sample.vue
<script setup lang="ts">
import { ref, watch } from 'vue';

const props = defineProps<{ hoge: Type }>();
const hoge = ref<Type>(props.hoge);

watch(() => props.hoge, () => {
  hoge.value = props.hoge;
});
</script>

ケースステディ

【OK】引数で受け取り

引数で受け取っても同様に作用します。

ok.vue
<script>
watch(() => props.hoge, (val) => {
  hoge.value = val;
});
</script>

【OK】Propsオブジェクトを監視

オブジェクト自体を監視対象にすることもできます。

ok.vue
<script>
watch(props, () => {
  hoge.value = props.hoge;
});
</script>

【OK】refの値を監視

refで設定した値を監視することもできます。

ok.vue
<script>
const fuga = ref<string>('');
watch(fuga, () => {
  // fugaが変更された時の処理内容
});
</script>

【NG】オブジェクトから特定のプロパティを指定

propsに限らず、特定のプロパティを指定しても監視できません。
指定したプロパティの値を渡すことになるためです。

NG.vue
<script>
// これらはNG例
const piyo = {count: 1}

watch(props.hoge, () => {
  hoge.value = props.hoge;
});
watch(piyo.count, () => {
  // 処理内容
});
</script>
13
3
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
13
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?