Consider a simple component Comp.vue file that only logs a message in the console when updated:

// Comp.vue

<script setup>
  import { onUpdated } from 'vue'
  onUpdated(() => {
    console.log('updated component')
  })
</script>
<template></template>

An App.vue file mounts Comp.vue and also logs a message in its onUpdated hook:

// App.vue

<script setup>
  import Comp from './Comp.vue'
  import { ref, onUpdated } from 'vue'

  onUpdated(() => {
    console.log('updated parent')
  })

  const text = ref('')
  const data = ref()
</script>

<template>
  <input v-model="text"/>
  <Comp/>
</template>

There's a text ref binded to an input element to trigger onUpdated on the parent. At this point, writing on the text input only logs 'updated parent' in the console.

If an object with a reactive property is passed to Comp as a prop, writing on the input text logs both 'updated component' and 'updated parent' in the console:

<Comp :data={ data }/>

That is, Comp's onUpdated hook is being triggered with changes to App's state. Here's a demo.

To avoid this, a computed property could be passed instead:

const computedData = computed(() => ({ data: data.value }))
// ...
<Comp :data="computedData"/>

However, I'd like to know why passing { data } directly causes Comp onUpdated hook to be triggered when text is updated.

0

There are 0 best solutions below