vue实现题号定位
Vue 实现题号定位的方法
在 Vue 中实现题号定位功能,可以通过以下几种方式实现:
使用锚点定位
通过 HTML 的锚点功能实现题号跳转。在 Vue 模板中为每个题目添加唯一的 ID,并通过 v-for 动态生成题目列表和锚点链接。
<template>
<div>
<div v-for="(question, index) in questions" :key="index">
<h3 :id="'question-' + index">{{ question.title }}</h3>
<p>{{ question.content }}</p>
</div>
<div class="question-nav">
<a
v-for="(question, index) in questions"
:key="index"
:href="'#question-' + index"
>
题号 {{ index + 1 }}
</a>
</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'
}
}
}
})
使用 JavaScript 平滑滚动
通过 scrollIntoView 方法实现平滑滚动效果,适合不需要改变路由的场景。
<template>
<div>
<div
v-for="(question, index) in questions"
:key="index"
:ref="'question-' + index"
>
<h3>{{ question.title }}</h3>
<p>{{ question.content }}</p>
</div>
<div class="question-nav">
<button
v-for="(question, index) in questions"
:key="index"
@click="scrollToQuestion(index)"
>
题号 {{ index + 1 }}
</button>
</div>
</div>
</template>
<script>
export default {
methods: {
scrollToQuestion(index) {
this.$refs[`question-${index}`][0].scrollIntoView({
behavior: 'smooth'
})
}
}
}
</script>
使用第三方库
可以引入第三方库如 vue-scrollto 实现更丰富的滚动效果。
安装库:
npm install vue-scrollto
使用示例:
import VueScrollTo from 'vue-scrollto'
Vue.use(VueScrollTo)
// 在组件中使用
this.$scrollTo('#question-1', 500, {
easing: 'ease-in-out',
offset: -50
})
动态高亮当前题号
结合 Vue 的响应式特性,可以动态高亮当前浏览的题号。
<template>
<div>
<div
v-for="(question, index) in questions"
:key="index"
:ref="'question-' + index"
@click="setActiveQuestion(index)"
:class="{ active: activeQuestion === index }"
>
<h3>{{ question.title }}</h3>
<p>{{ question.content }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
activeQuestion: null
}
},
methods: {
setActiveQuestion(index) {
this.activeQuestion = index
}
}
}
</script>






