我正在与 Vue Router(在我的例子中是 4.2 版本)进行斗争。我想实现当用户从导航返回到另一条路线时,恢复原始垂直位置。
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
if (from.hash) {
console.log('Scroll to Hash', from.hash);
return {
el: from.hash,
behavior: 'smooth',
offset: { x: 0, y: 160 },
};
} else if (savedPosition) {
console.log('Saved Position', savedPosition);
return savedPosition;
使用此配置,我可以在路由中包含哈希,以确保当用户返回时,原始位置部分恢复。问题是浏览器向下滚动到该元素,但滚动得太远,使实际元素隐藏在视图顶部上方。
然而,虽然官方文档提到了应用
offset
的参数,但似乎被忽略了。
我尝试了 Y 轴的各种值,但似乎没有任何效果。
我查看了 Vue Router v4.2 的存储库,看来 offset 参数已被删除。
有替代方案吗?
路由器源代码中的相应类型确认不再有一个名为“offset”的参数。如果没有它,滚动体验就会受到严重影响。
vue-router 4.2 的原始代码:
declare type ScrollPosition = ScrollPositionCoordinates | ScrollPositionElement;
/**
* Scroll position similar to
* {@link https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions | `ScrollToOptions`}.
* Note that not all browsers support `behavior`.
*/
declare type ScrollPositionCoordinates = {
behavior?: ScrollOptions['behavior'];
left?: number;
top?: number;
};
declare interface ScrollPositionElement extends ScrollToOptions {
/**
* A valid CSS selector. Note some characters must be escaped in id selectors (https://mathiasbynens.be/notes/css-escapes).
* @example
* Here are a few examples:
*
* - `.title`
* - `.content:first-child`
* - `#marker`
* - `#marker\~with\~symbols`
* - `#marker.with.dot`: selects `class="with dot" id="marker"`, not `id="marker.with.dot"`
*
*/
el: string | Element;
}
根据3年前的GitHub问题,我们必须区分Safari和Chrome,并且必须同时使用:
top
和offset
return {
el: from.hash,
behavior: 'smooth',
top: 100,
offset: { x: 0, y: 100 },
在官方存储库的类型定义中找不到这两个属性,但它似乎可以正常工作。