How could I watch a prop in the composition api?

Viewed 6345

How can I call a function when a prop is updated?

parent container:

<div>     
  <Maintable :type="typeRef" :country="countryRef" />
</div>

child container:

    export default{

    props: ['type'],
    
    setup(props)
    {   
        watch(props.type, () => {
            console.log('hello')
        })
    }

this code gets an error: Invalid watch source... How can I listen for an update of tthe props?

Hope someone can help me out!! :-)

2 Answers

Try to return the prop from function as first parameter :

    export default{

    props: ['type'],
    
    setup(props)
    {   
        watch(()=>props.type, (newVal) => {
            console.log('hello')
        })
    }

Instead of watch(props.type, do watch(()=>props.type, because ()=>props.type is an arrow function that return the prop and it's the parameter of the watcher property

You have two possible solutions:

  1. Your can make a computed property and watch it

import {computed, watch} from 'vue';

export default {
  props: ['type'],

  setup(props) {
    const type = computed(() => props.type);

    watch(type, (newValue) => {
      console.log('hello');
    });
  }
}

  1. You can use arrow function like this

import {watch} from 'vue';

export default {

  props: ['type'],

  setup(props) {   
    watch(() => props.type, (newValue) => {
        console.log('hello');
    });
  }
}

Related