① 首先,在 Vue Router 的路由配置中,需要将 mode 设置为 hash
const router = new VueRouter({
mode: 'hash',
routes: [] // 路由配置
})
② 在页面跳转时,使用 router.push 方法进行路由跳转,设置目标 URL 的 hash 部分为锚点的名称
toRegister() {
this.$router.push('/register?type=2#applicationMsg')
},
③ 在目标组件中,可以使用 Vue 的生命周期函数 mounted 来获取目标描点的 DOM 元素,并使用
scrollIntoView方法将其滚动到视图中
mounted() {
const ref = this.$refs.applicationMsg
if (ref) {
ref.scrollIntoView()
}
}
这样,当路由跳转到目标页面时,页面会自动滚动到指定的锚点位置。