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
VueJS $watch $refs
提问by Kiee
Is it possible to $watch
Vue $refs
?
可以用$watch
Vue$refs
吗?
I'm wanting to set logic against a child component that is nested inside my current Vue instance but inside the ready
callback, $refs.childcomponent
is initially undefined
while 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
结果:错误:超出最大调用堆栈
watch
property 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)
}
)