我相信你是在问直接跳转到页面的某个特定区域,通过导航到页面中的锚定标签,比如#section-3
.
要使其工作,您需要修改scrollBehavior函数,如下所示:
new VueRouter({
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
if (to.hash) {
return {selector: to.hash}
//Or for Vue 3:
//return {el: to.hash}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: '/', component: abcView},
// your routes
]
});
参考:https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling
我试图创建一个JSFIDLE示例,但由于mode:'history'
的原因,它不起作用.如果您复制代码并在本地运行,您将看到它是如何工作的:https://jsfiddle.net/mani04/gucLhzaL/
通过在scrollBehavior中返回{selector: to.hash}
(或Vue 3中的{el: to.hash}
),您将把锚标记哈希传递到下一个路由,该路由将导航到该路由中的相关部分(使用id
标记).