Javascript VueJS $watch $refs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39035498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:08:12  来源:igfitidea点击:

VueJS $watch $refs

javascriptvue.js

提问by Kiee

Is it possible to $watchVue $refs?

可以用$watchVue$refs吗?

I'm wanting to set logic against a child component that is nested inside my current Vue instance but inside the readycallback, $refs.childcomponentis initially undefinedwhile it's processed.

我想针对嵌套在我当前 Vue 实例中但在ready回调内部的子组件设置逻辑,$refs.childcomponent最初是undefined在处理它时。

inside ready()

里面 ready()

this.$watch('$refs', function() {
    console.log("not firing");
}, { deep: true });

Result: Error: Maximum call stack exceeded

结果:错误:超出最大调用堆栈

watchproperty of the instance

watch实例的属性

watch: {
  '$refs': {
     handler: function() { console.log("hit"); },
     deep: true
  }
}

result: nothing.

结果:没有。

回答by kenberkeley

You can $watch$refs.<name>.<data>but not $refs.<name>itself, not to mention $refs.

你可以$watch$refs.<name>.<data>但不能$refs.<name>本身,更不用说$refs

https://jsfiddle.net/kenberkeley/9pn1uqam/

https://jsfiddle.net/kenberkeley/9pn1uqam/

const Counter = {
  data: () => ({
    i: 0
  }),
  template: `<fieldset>
    <p>Counter</p>
    <code>i = {{ i }}</code>
    <button @click="i += 1"> Add One </button>
  </fieldset>`
}

const App = {
  components: { Counter },
  mounted () {
    this.$watch(
        () => {
            return this.$refs.counter.i
        },
      (val) => {
        alert('App $watch $refs.counter.i: ' + val)
      }
    )
  },
  template: `<fieldset>
    <p>App</p>
    <counter ref="counter" />
  </fieldset>`
}

new Vue({
    el: '#app',
    render: h => h(App)
})

回答by Linus Borg

No, $refs are not reactive, watch won't work.

不,$refs 没有反应性,watch 不起作用。

回答by Ian Pinto

In mounted use code below:

在下面的安装使用代码中:

this.$watch(
        () => {
            return this.$refs.<name>.<data>
        },
      (val) => {
        alert('$watch $refs.<name>.<data>: ' + val)
      }
    )