0

I have watcher with the same name as a prop. The prop is dynamically set in a parent component on some event. I need something that triggers some function in the child component with property value every time the event is triggered on parent -even if the prop it set is the same. Is there any watcher option or other method of handling such case which would allow me to do that ?

What I tried (this is in Post component):

watch: {
    replyClicked:
    {
        handler(newVal, oldVal)
        {
            console.log(newVal, oldVal);
        },
        immediate:true
    }
},

the console.log only prints when newVal is different from oldVal, I need some function to trigger even if they are the same. The parent component looks like this:

<RenderPost @onReply="onReply" />
<Post :replyClicked="replyClicked" />

and these are the parent data and method:

data()
{
    return {
        replyClicked : null
    }
},
methods :
{
    onReply(id)
    {
        this.replyClicked = id;
    }
}
Robert C. Holland
  • 1,651
  • 4
  • 24
  • 57

1 Answers1

4

You could use immediate option :

watch:{
  yourProp:{
   handler(newval,oldVal){

   },
   immediate:true,
   deep:true //if the prop is an object or an array

 }

}

EDIT

since the old value is the same as the new one, you could try this workaround, by defining the prop as an object by adding a field that always changes :

data()
{
    return {
        replyClicked : {
          changeCount:0,
          id:null
         }
    }
},
methods :
{
    onReply(id)
    {
        this.replyClicked ={id, changeCount:this.replyClicked.changeCount+1}
    }
}

child component :

watch: {
    replyClicked:
    {
        handler(newVal, oldVal)
        {
            console.log(newVal, oldVal);
        },
        immediate:true,
        deep:true
    }
},
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • 1
    To clarify: remember that `watch` with `immediate: true` fires before `hook:created` – Adam Orłowski Dec 08 '20 at 11:18
  • 1
    `immediate` only means the watcher runs during component creation. It is not related to whether it will be triggered with events that don't change the prop, which is what OP is asking about – Dan Dec 08 '20 at 11:34