我有下一个项目。当我将路线从http://localhost:3000/catalog/postery
更改为http://localhost:3000/catalog/postery/all?photos%5B%5D=262
时,我的页面向上滚动到顶部,并且只有在我的路线更改后
我的文件scrollBehavior.js:
export default async function (to, from, savedPosition) {
if (
(to.path.indexOf("/catalog/") !== -1 &&
to.path.indexOf("/all") === -1 &&
Object.keys(to.query).length > 0) ||
(to.path.indexOf("/search") !== -1 && Object.keys(to.query).length > 0) ||
(to.name === "product-type-id" && Object.keys(to.query).length > 0) ||
(from.name === "product-type-id" &&
to.name === "product-type-id" &&
to.params.type != from.params.type)
) {
return;
}
if (to.path.indexOf("/catalog/") !== -1 && savedPosition != null) {
return { x: 0, y: savedPosition.y };
}
return { x: 0, y: 0 };
}
如何防止在更改路由之前向上滚动?
所以,你需要:
- 点击链接
- 开始渲染页面
- 滚动到顶部
从Vue路由器文档来看,你可以使用这样的代码
/app/router.scrollBehavior.js
export default function () {
return { x: 0, y: 0, behavior: 'smooth' }
}
你也可以使它成为有条件的或者像这样的setTimeout
export default function (to, from, savedPosition) {
if (to.path === '/my-cool-path') {
return { x: 0, y: 0, behavior: 'smooth' }
}
}
export default function (to, from, savedPosition) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ x: 0, y: 0, behavior: 'smooth' })
}, 2000)
})
}
使用vue-scrollto
的答案也可能有所帮助。
最后的手段是使用一些过渡来隐藏丑陋的抖动/加载,这实际上是非常性感的。