vue实现题号定位
Vue 实现题号定位的方法
在 Vue 中实现题号定位功能,可以通过以下几种方式实现:
使用 ref 和 scrollIntoView
通过给每个题目元素添加 ref 属性,并使用 scrollIntoView 方法滚动到指定题目位置。
<template>
<div>
<button @click="scrollToQuestion(1)">跳转到题号1</button>
<div v-for="i in 5" :key="i" :ref="`question${i}`">
题目 {{ i }}
</div>
</div>
</template>
<script>
export default {
methods: {
scrollToQuestion(num) {
this.$refs[`question${num}`][0].scrollIntoView({
behavior: 'smooth'
});
}
}
};
</script>
使用锚点 (<a> 标签)
通过动态生成锚点链接实现题号定位。
<template>
<div>
<a v-for="i in 5" :key="i" :href="`#question${i}`">
跳转到题号 {{ i }}
</a>
<div v-for="i in 5" :key="i" :id="`question${i}`">
题目 {{ i }}
</div>
</div>
</template>
使用 Vue Router 的滚动行为
如果题目分布在多个路由页面,可以通过 Vue Router 的 scrollBehavior 实现定位。
const router = new VueRouter({
routes: [...],
scrollBehavior(to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth'
};
}
}
});
结合动态组件和状态管理
对于复杂的题目导航,可以结合 Vuex 或 Pinia 管理当前题目位置,并通过计算属性动态渲染题目内容。

import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const currentQuestion = ref(1);
const questions = [1, 2, 3, 4, 5];
const goToQuestion = (num) => {
currentQuestion.value = num;
const el = document.getElementById(`question${num}`);
if (el) el.scrollIntoView({ behavior: 'smooth' });
};
return { currentQuestion, questions, goToQuestion };
}
});
注意事项
- 如果题目内容动态加载,确保 DOM 渲染完成后再执行定位操作,可在
nextTick中调用滚动方法。 - 对于移动端,测试
scrollIntoView的兼容性,必要时使用 polyfill。 - 锚点方式在单页应用 (SPA) 中可能需要额外处理,避免页面刷新。






