vue 获取 for循环动态设置ref的属性及获取该元素到顶部的距离

该博客介绍了如何在Vue中使用`v-for`指令动态设置`ref`属性,并展示了如何遍历数据来获取特定元素,当元素值匹配条件时,利用`scrollTo`实现元素平滑滚动到视口位置。这对于实现列表滚动定位功能具有实践意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 动态设置ref
<template v-for="(item, index) in data">
    <div :key="index" :ref="item.id">
    {{ item.value }}
    </div>
 </template>
  1. 根据ref获取元素(需要添加[0])
data.forEach(item => {
	if (iteam.value === 'a') {
		// 滚动到元素位置
		window.scrollTo({
	     top: this.$refs[item.id][0].getBoundingClientRect().top + window.scrollY, 
	     behavior: 'smooth' // 平滑滚动
	   })
	}
})
### 实现无限循环滚动公告组件 为了实现一个能够无限循环滚动的公告组件,在 Vue 3 中可以利用 Composition API 和一些自定义逻辑来完成这一目标。下面是一个详细的解决方案。 #### 组件设计思路 该组件应具备以下特性: - 自动无限循环滚动 - 鼠标悬停时暂停滚动,离开后恢复 - 支持配置滚动速度、时间间隔等参数 - 当内容不足以填满容器时不启动自动滚动 #### 完整代码示例 ```vue <template> <div class="notice-container" @mouseenter="pauseScroll()" @mouseleave="resumeScroll()"> <ul ref="scrollListRef"> <li v-for="(item, index) in items.concat(items)" :key="index">{{ item }}</li> </ul> </div> </template> <script setup lang="ts"> import { onMounted, onUnmounted, ref } from 'vue' interface Props { speed?: number // 单位像素/秒,默认值为1px/s } const props = withDefaults(defineProps<Props>(), { speed: 1, }) let scrollIntervalId: NodeJS.Timeout | null = null const scrollListRef = ref<HTMLUListElement | null>(null) function startAutoScroll() { if (!scrollListRef.value || !props.speed) return const step = () => { if (scrollListRef.value) { let offsetTop = scrollListRef.value.offsetTop; // 设置向上偏移量 scrollListRef.value.style.transform = `translateY(${offsetTop}px)` // 如果已经到达顶部,则重置位置 if (-offsetTop >= scrollListRef.value.clientHeight / 2) { scrollListRef.value.style.transition = "none"; scrollListRef.value.style.transform = "translateY(0)"; requestAnimationFrame(() => { scrollListRef.value!.style.removeProperty('transition'); }); } } setTimeout(step, Math.abs(props.speed * 10)) } step() scrollIntervalId = setInterval(step, Math.abs(props.speed * 10)) as unknown as NodeJS.Timeout } // 暂停滚动函数 function pauseScroll() { clearInterval(scrollIntervalId!) scrollIntervalId = null } // 恢复滚动函数 function resumeScroll() { startAutoScroll() } onMounted(() => { nextTick().then(() => { startAutoScroll() }) }) onUnmounted(() => { if (scrollIntervalId !== null) { clearInterval(scrollIntervalId) } }) const items = ['这是第一条公告', '这是第二条公告', '这是第三条公告'] </script> <style scoped> .notice-container { width: 300px; height: 80px; overflow: hidden; border: solid 1px #ccc; } ul { list-style-type: none; padding-left: 0; margin-top: 0; transition: transform .5s ease-in-out; } li { line-height: 40px; text-align: center; } </style> ``` 此代码实现了基本的功能需求,并通过监听`mouseenter`和`mouseleave`事件来控制滚动行为的变化[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值