【问题标题】:Vue3 cannot get dom via attribute refVue3 无法通过属性 ref 获取 dom
【发布时间】:2021-12-31 06:45:01
【问题描述】:
     <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时,你可能无法通过ref获取dom。我没有解决办法,请帮帮我

【问题讨论】:

    标签: typescript vuejs3


    【解决方案1】:

    直到v-iffalse 渲染到true 之后才会创建ref

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

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

    您可以查看条件,然后使用nextTick 获取ref

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

    最后,您可以观看 ref 本身

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      相关资源
      最近更新 更多