【发布时间】:2019-10-24 05:47:54
【问题描述】:
当我更改路由的查询参数(以及视图的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);
});
},
【问题讨论】:
-
看来你的组件高度不是在router变化的时候决定的。您的组件中是否有任何异步加载?
标签: vue.js vuejs2 vue-component vue-router