vue表格实现锚点
实现 Vue 表格锚点功能的方法
核心思路
通过动态绑定 id 或 ref,结合 scrollIntoView 或第三方库实现表格内跳转定位。
方法一:使用原生 scrollIntoView
通过为表格行或单元格设置唯一 id,点击锚点时滚动到目标位置。
<template>
<div>
<!-- 锚点链接 -->
<div v-for="item in data" :key="item.id">
<a @click="scrollTo(item.id)">跳转到 {{ item.name }}</a>
</div>
<!-- 表格内容 -->
<table>
<tr v-for="item in data" :key="item.id" :id="`row-${item.id}`">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
data: [
{ id: 1, name: 'A', value: 100 },
{ id: 2, name: 'B', value: 200 }
]
}
},
methods: {
scrollTo(id) {
const element = document.getElementById(`row-${id}`);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
}
}
</script>
方法二:结合 Vue 的 ref 属性
通过 ref 绑定动态引用,避免直接操作 DOM。

<template>
<div>
<div v-for="item in data" :key="item.id">
<a @click="scrollTo(item.id)">跳转到 {{ item.name }}</a>
</div>
<table>
<tr v-for="item in data" :key="item.id" :ref="`row-${item.id}`">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return { /* 同方法一 */ }
},
methods: {
scrollTo(id) {
const ref = this.$refs[`row-${id}`];
if (ref && ref[0]) {
ref[0].scrollIntoView({ behavior: 'smooth' });
}
}
}
}
</script>
方法三:固定表头场景的偏移补偿
若表格有固定表头,需计算偏移量避免遮挡。
scrollTo(id) {
const element = document.getElementById(`row-${id}`);
if (element) {
const offset = 60; // 表头高度
const topPos = element.offsetTop - offset;
window.scrollTo({ top: topPos, behavior: 'smooth' });
}
}
方法四:使用第三方库(如 vue-scrollto)
简化滚动逻辑,支持更多配置。

-
安装库:
npm install vue-scrollto -
实现代码:
<template> <div> <div v-for="item in data" :key="item.id"> <a v-scroll-to="`#row-${item.id}`">跳转到 {{ item.name }}</a> </div> <table> <tr v-for="item in data" :key="item.id" :id="`row-${item.id}`"> <td>{{ item.name }}</td> <td>{{ item.value }}</td> </tr> </table> </div> </template>
注意事项
- 性能优化:大数据量时建议使用虚拟滚动(如
vue-virtual-scroller)。 - 浏览器兼容性:
scrollIntoView的smooth参数在旧浏览器需 polyfill。 - 路由冲突:避免锚点
id与路由哈希冲突。






