Sau*_*abh 14 html javascript vue.js
我正在创建一个小的Vue webapp,我想在此创建一个锚标签.
我给了id一个div我希望有这样的锚标签:
<div id="for-home">
....
</div>
Run Code Online (Sandbox Code Playgroud)
这是我的路由器配置:
export default new Router({
abstract: true,
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: [
{ path: '/', component: abcView}
]
})
Run Code Online (Sandbox Code Playgroud)
但是这个锚标签有时会工作,有时候不起作用,我错过了什么吗?
Man*_*ani 36
我相信你要求直接跳到页面的特定区域,通过导航到#section-3页面内的锚标签.
为此,您需要修改scrollBehavior函数,如下所示:
new VueRouter({
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
if (to.hash) {
return {selector: to.hash}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: '/', component: abcView},
// your routes
]
});
Run Code Online (Sandbox Code Playgroud)
参考:https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling
我试图创建一个jsFiddle示例但由于它没有工作mode:'history'.如果您复制代码并在本地运行,您将看到它是如何工作的:https://jsfiddle.net/mani04/gucLhzaL/
通过{selector: to.hash}在scrollBehavior中返回,您将把锚标记哈希传递给下一个路由,该路由将导航到该路由中的相关部分(标记为使用id).
对我来说,{selector: to.hash}解决方案只是拒绝与 vue-router 4.0.0 一起使用。以下方法有效并且还启用了平滑滚动。
500ms 的超时是为了允许页面加载,因为我发现否则平滑滚动不会滚动到正确的位置(因为页面仍在加载)。
const scrollBehavior = (to, from, savedPosition) => {
if (to.hash) {
setTimeout(() => {
const element = document.getElementById(to.hash.replace(/#/, ''))
if (element && element.scrollIntoView) {
element.scrollIntoView({block: 'end', behavior: 'smooth'})
}
}, 500)
//NOTE: This doesn't work for Vue 3
//return {selector: to.hash}
//This does
return {el: to.hash};
}
else if (savedPosition) {
return savedPosition
}
return {top: 0}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13327 次 |
| 最近记录: |