How to watch child properties changes from parent component
Asked Answered
A

2

18

I am using a date picker component library and i want to watch when a property of that component changes.

I have tried this:

  watch: {
    '$refs.picker.popupVisible': {
      handler (new_value) {
        console.log('executed')
      },
      deep: true
    }
  }

Also this:

  computed: {
    picker () {
      console.log(this.$refs.picker.popupVisible)
      return this.$refs.picker.popupVisible
    }
  }

I know that the solution will be a vue.js hack because this is not the right way.If i had access to child component i would emit en event to parent but unfortunately i don't have.

Accumulation answered 7/7, 2018 at 17:19 Comment(0)
D
27

I had a similar problem using a library which had some limitations.

Unfortunately, your watcher will not work.You have to use the function watcher to make this to work.And you have to use it inside the mounted hook.

  mounted() {
    this.$watch(
      "$refs.picker.popupVisible",
      (new_value, old_value) => {
         //execute your code here
      }
    );
  }

I also have an example. Please take a look here

Drawback answered 7/7, 2018 at 17:26 Comment(4)
Is there an explanation on why watch: {} won't work?Dekow
I am not sure but I guess watch: {} can be used for components properties whilst vm.$watch() it is not limited to the component instance. So in that case watching from parent, child properties for changes with watch: {} it does not work. vm.$watch() works perfect though.Drawback
I suspect it doesn't work because at the time watch{} is created, the child components haven't been mounted, and therefore the reactivity can't be set up. By doing it with this.$watch(), that is happening after the child components have mounted, so the reactivity does work.Finnougric
Should we also unwatch this in beforeDestroy?Sharasharai
E
1

What you can do is create a data object in parent component and include the date field in that data object and pass that data object to child component as props

<child :dateObj="dateObj"></child>
data: {
  dateObj: {
    date: ""
  }
}

And in child component you can use the date field of that dateObj props. This is possible because Vue doesn't watch the property of Objects passed as props and we can modify them without Vue complaining in console.

Thus the changed date field is reflected in parent as well.

Eastman answered 21/12, 2020 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.