有可能去$watch Vue $refs吗
我希望针对嵌套在当前Vue实例中的子组件设置逻辑,但在ready回调中,$refs.childcomponent在处理时最初是undefined。
ready()内部的
this.$watch('$refs', function() {
console.log("not firing");
}, { deep: true });结果:错误:超过最大调用堆栈
实例watch 属性
watch: {
'$refs': {
handler: function() { console.log("hit"); },
deep: true
}
}结果:没什么。
发布于 2017-07-10 12:25:02
您可以使用$watch $refs.<name>.<data>,但不能使用$refs.<name>本身,更不用说$refs了。
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)
})发布于 2018-06-01 07:14:17
在以下安装使用代码中:
this.$watch(
() => {
return this.$refs.<name>.<data>
},
(val) => {
alert('$watch $refs.<name>.<data>: ' + val)
}
)发布于 2020-10-26 21:22:12
这方面有一项工作要做。考虑到当将数组赋值给变量时,JavaScript没有创建数组的副本,它只是创建了对原始数组的引用。知道Vue的$refs是数组,我们可以执行以下操作:
<template>
<div>
<ul v-if="showAvailable">
<li v-for="pet in allPets.available" :key="pet.id" ref="pets">
{{ pet.name }}
</li>
</ul>
<ul v-else>
<li v-for="pet in allPets.unavailable" :key="pet.id" ref="pets">
{{ pet.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['allPets'],
data() {
showAvailable: true // Normally would change from a button or something
shownPets: null // set to null for now
},
mounted() {
this.$set(this.$data, 'shownPets', this.$refs.pets);
},
watch: {
shownPets: {
handler(newVal, oldVal){
// Do something when the DOM changes!
},
deep: true
}
}
}
</script>还有哇哦。在组件挂载后,我们将数据shownPets设置为pets $ref。根据showAvailable是true还是false,引用将包含不同的元素,现在我们可以查看$ref或DOM的更改。
https://stackoverflow.com/questions/39035498
复制相似问题