当我更改路由的查询参数(和视图的props
(时,如何防止页面滚动到顶部?
我尝试了以下方法,但没有运气:
尝试 1 - 路由的组件
当我将超时设置为任意大的数字(1 秒(时,它会在一段时间延迟后向下滚动。
// in my route's component
props: {...},
watch: {
$route(to, from) {
let y = window.scrollY;
this.$nextTick(() => {
setTimeout(() => {
console.log(`scrolling to ${y}`);
window.scrollTo(0, y);
}, 0);
});
}
}
尝试 2 - $router的scrollBehavior
这将记录正确的y
值,但不保留旧位置。
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
}
if (from.path !== to.path) {
return { x: 0, y: 0 };
}
let existing = {
x: window.scrollX,
y: window.scrollY
};
console.log(`Existing scroll`, existing);
return new Promise(resolve => {
setTimeout(() => {
resolve(existing);
}, 0);
});
},
我刚刚找到了答案。这是我的代码。默认行为将滚动到顶部,除非您传递自定义params
,如果提供了path
,路由器将忽略该(https://router.vuejs.org/guide/essentials/navigation.html(。
scrollBehavior (to, from, savedPosition) {
// savedPosition is only available for popstate navigations.
if (savedPosition) return savedPosition
// if the returned position is falsy or an empty object,
// will retain current scroll position.
if (to.params.savePosition) return {}
// scroll to anchor by returning the selector
if (to.hash) {
let position = {selector: to.hash}
// specify offset of the element
// if (to.hash === '#anchor2') {
// position.offset = { y: 100 }
// }
return position
}
// scroll to top by default
return {x: 0, y: 0}
}
如果你返回一个假的或空的物体,Vue 路由器将返回原始位置。然后,我将传递一个自定义params
,我将其命名为"savePosition"传递给params
。
this.$router.push({ query: query, params: { savePosition: true } })
这样,默认情况下,您的路由器将滚动到顶部,除非您将savePosition
传递给params
,或者如果您传递哈希。
对其他答案的备注:
1. hashbag: true,
.在当前版本的 vue-router 文档中,我既找不到hashbag
也没有hashbang
。可能这是一个古老的属性。
2. if (to.params.savePosition) return {}
+ this.$router.push({ query: query, params: { savePosition: true } })
无需使用其他参数,savePosition
解决此问题。
我的回答和评论:
const router = new VueRouter({
mode: 'history', // or 'hash'
routes,
scrollBehavior (to, from, savedPosition) {
// Exists when Browser's back/forward pressed
if (savedPosition) {
return savedPosition
// For anchors
} else if (to.hash) {
return { selector: to.hash }
// By changing queries we are still in the same component, so "from.path" === "to.path" (new query changes just "to.fullPath", but not "to.path").
} else if (from.path === to.path) {
return {}
}
// Scroll to top
return { x: 0, y: 0 }
}
})
如果您不想在参数更改时滚动到顶部。您可以检查to
并next
路径是否相等。
scrollBehavior(to, from, savedPosition) {
if (to.path != from.path) {
return { x: 0, y: 0 };
}
}
尝试使用导航卫士
// in your router.js or whatever your router config is
var clientY = 0
router.beforeEach((next) => {
clientY = window.scrollY
next()
})
router.afterEach(() => {
window.scrollTo(0,clientY)
})
有类似的问题,只有在添加模式时才对我有用:历史记录和哈希包:真。以下是 VueRouter 设置的外观:
mode: 'history',
hashbag: true,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { x: 0, y: 0 }
}
},
希望对您有所帮助。