Search code examples
vue-componentvuejs3

Updating prop value in child component when parent property updates Vue 3


I'm having troubles to update the value of a prop in a child component, the documentation says "when the parent property updates, it will flow down to the child" but that is not happening, i've made a summary of the code:

Parent's:

<script setup>
  import Child from "../components/Child.vue"
  
  var counter = 0

  setInterval(() => {
    counter++
    console.log(counter)
  }, 2000)

</script>

<template>
    <Child :counter="counter"/>
</template>

Child's:

<script setup>
    import { ref } from "vue"

    const props = defineProps(['counter'])

    const count = ref(props.counter)
</script>

<template>
    <h1>{{ count }}</h1>
</template>

Anyone knows what could be wrong? I already tried to pass a ref object to the child and to put a watch function on the prop but it didn't work


Solution

  • The antwort from Gaetan C. is right, but not enough.

    The counter data property is not reactive and changing it will not trigger updates.

    var counter = 0;
    

    should be

    const counter = ref(0);
    

    and then

    counter.value++;
    

    Here is the playground

    const { createApp, ref } = Vue;
    
    const Child = {
      props: ['counter'],
      template: '<h1>{{ counter }}</h1>'
    }
    
    const App = {
      components: { 
        Child
      },
      setup() {    
        const counter = ref(0);
        
        setInterval(() => {
          counter.value++
        }, 2000)
        
        return { counter }
      }
    }
    
    const app = createApp(App)
    app.mount('#app')
    <div id="app">  
        <child :counter="counter"></child>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>