Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch child properties changes from parent component

Tags:

vue.js

vuejs2

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.

like image 421
Ready Dev Avatar asked Jul 07 '18 17:07

Ready Dev


2 Answers

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

like image 94
Roland Avatar answered Oct 08 '22 01:10

Roland


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.

like image 29
Ramesh Maharjan Avatar answered Oct 08 '22 00:10

Ramesh Maharjan