Vue3无法通过属性引用获取dom


<template>
<div class="music-list">
<template v-if="songs.length">
<scroll :options="scrollOptions" v-if="songs.length" @scroll="onScroll" ref="scrollRef">
<song-list
v-if="songs.length"
:songs="songs"
:playlist="playlist"
class="song-list-ref"
@scroll="onScroll"
>
</song-list>
</scroll>
</template>
</div>
</template>
const { songs, playlist, creator, resolvedIcons } = useRouterHook(Icons)
const scrollRef = ref<any>(null)
function onScroll(pos: any): void {
const y: number = -pos.y
console.log(scrollRef)
}

当我尝试获取scrollRef.value时,它返回true,有时它会返回null

我在网上搜索了这个问题,有人说当你使用v-if时,你可能无法通过参考获得dom。我没有解决方案,请帮助我

只有在v-iffalse渲染到true之后,才会创建ref

使用v-show而不是v-if以确保始终渲染元素。

使用v-if:时跟踪ref的其他选项

您可以观察条件,然后使用nextTick获得ref

watch(()=>songs.length, value=>{
if (value > 0) {
nextTick(()=>{
// use ref
})
}
})

最后,你可以观看裁判本身

watch(ref, value=>{
if (value) {
}
})

最新更新