如何从父组件观察子属性的变化 [英] How to watch child properties changes from parent component

查看:24
本文介绍了如何从父组件观察子属性的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用日期选择器组件库,我想观察该组件的属性何时发生变化.

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

我已经试过了:

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

还有这个:

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

我知道解决方案将是 vue.js hack,因为这不是正确的方法.如果我可以访问子组件,我会向父组件发出 en 事件,但不幸的是我没有.

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.

推荐答案

我在使用一个有一些限制的库时遇到了类似的问题.

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

不幸的是,您的观察者无法工作.您必须使用函数观察者才能使其工作.您必须在mounted钩子内使用它.

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
      }
    );
  }

我也有一个例子.请看看这里

这篇关于如何从父组件观察子属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆