我是 Vue 新手,正在尝试使用 $refs 从同级组件中获取 DOM 中的一些元素(出于非常基本的目的,只是为了获取它们的高度等),并且我是在计算中这样做的。
无论我尝试什么,this.$root.$refs要么总是以未定义的形式返回,要么作为空对象返回,而且我不知道我做错了什么。
在父组件中,我有:
<template>
<ComponentA />
<ComponentB />
</template>
Run Code Online (Sandbox Code Playgroud)
AI 组件中有:
<template>
<div id="user-nav">
<div ref="nav-container">
<slot />
</div>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
我只是尝试看看是否可以通过控制台日志记录在 ComponentB 中访问它
console.log(this.$root.$refs);
Run Code Online (Sandbox Code Playgroud)
在该组件的安装函数中。
但我不断得到一个空物体。
你能不能像这样跨同级组件访问东西吗???
我的组件数量取决于数组数量,因此当我向数组添加新项目时,它应该创建新组件。
创建新组件时,我想获得有关它的参考,这就是我产生误解的地方。最后添加的组件是undefined当我尝试获取它时。
但是,如果我想在一段时间后获得参考,它会起作用。我猜是因为异步,但是我不确定。
为什么会发生这种情况,以及是否有避免使用的方法setTimeout?
<div id="app">
<button @click="addNewComp">add new component</button>
<new-comp
v-for="compId in arr"
:ref="`components`"
:index="compId"
></new-comp>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}</h1>
</script>
Run Code Online (Sandbox Code Playgroud)
Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[1,2,3,4]
},
methods:{
addNewComp:function(){
let arr = this.arr;
let components = this.$refs.components;
arr.push(arr.length+1);
console.log("sync",components.length);
console.log("sync",components[components.length-1])
setTimeout(() => {
console.log("async",components.length);
console.log("async",components[components.length-1])
}, 1);
}
}
})
Run Code Online (Sandbox Code Playgroud)