You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3.2 Script Setup中动态$ref的实现问题求助

Vue3.2 Script Setup 实现动态目录平滑滚动方案

方案一:用对象Ref统一管理(推荐)

不用手动逐个定义categorie0到categorie7的ref,直接用一个对象ref批量存储所有目录元素,更简洁灵活:

  1. Script Setup 代码
<script setup>
import { ref } from 'vue'

// 定义对象ref存储所有分类元素
const categoryRefs = ref({})

// 滚动到指定分类的方法
const scrollToCategory = (refName) => {
  const targetEl = categoryRefs.value[refName]
  if (targetEl) {
    // 平滑滚动到目标元素,可通过block参数控制对齐方式
    targetEl.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}
</script>
  1. 模板代码
    不管目录是循环生成还是手动编写,绑定对应ref和点击事件即可:
<template>
  <!-- 目录列表 -->
  <ul class="directory">
    <li v-for="i in 8" :key="i" @click="scrollToCategory(`categorie${i-1}`)">
      分类 {{ i }}
    </li>
  </ul>

  <!-- 对应内容区块 -->
  <div 
    v-for="i in 8" 
    :key="i" 
    :ref="el => el && (categoryRefs.value[`categorie${i-1}`] = el)" 
    class="category-block"
  >
    分类 {{ i }} 的内容...
  </div>
</template>

方案二:适配已手动定义的单个Ref

如果你已经提前定义了categorie0到categorie7这些单独的ref,可以把它们整合到一个对象中,再动态调用:

<script setup>
import { ref } from 'vue'

// 你已有的单个ref实例
const categorie0 = ref(null)
const categorie1 = ref(null)
// ... 依次定义到 categorie7 = ref(null)

// 将所有ref整合到对象中
const categoryRefs = {
  categorie0,
  categorie1,
  categorie2,
  categorie3,
  categorie4,
  categorie5,
  categorie6,
  categorie7
}

// 滚动方法
const scrollToCategory = (refName) => {
  const targetEl = categoryRefs[refName].value
  if (targetEl) {
    targetEl.scrollIntoView({ behavior: 'smooth' })
  }
}
</script>

模板中的点击逻辑和方案一一致,直接调用scrollToCategory('categorieX')即可。

核心说明

  • 动态绑定ref时,使用:ref="el => ..."的函数形式,能将元素实例存入对象的指定键位,替代Vue2中this.$refs[refName]的写法。
  • scrollIntoView的behavior: 'smooth'是实现平滑滚动的关键参数,block参数可控制滚动后元素的对齐位置(如start顶部对齐、center居中对齐)。

内容的提问来源于stack exchange,提问作者Shoooryuken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:35:24