使用Vue Router的Hash模式可以实现锚点跳转。
1. 首先,在Vue Router的路由配置中,需要将mode设置为hash:
const router = new VueRouter({
mode: 'hash',
routes: [
// 路由配置
]
})
2. 然后,在需要跳转的地方,使用router.push方法进行路由跳转,设置目标URL的hash部分为锚点的名称:
this.$router.push({ path: '/xxxx#锚点名称' })
3.接着, 在目标组件中,可以使用Vue的生命周期函数mounted来获取目标锚点的DOM元素,并使用scrollIntoView方法将其滚动到视图中:
mounted () {
const anchor = document.getElementById('锚点名称')
if (anchor) {
anchor.scrollIntoView()
}
}