【发布时间】:2021-09-29 11:51:09
【问题描述】:
我想做什么? 我想记住用户在页面上的当前位置,因此一旦她/他导航到另一个页面,然后使用浏览器“返回”按钮返回以滚动到该位置。请注意,仅当用户单击浏览器后退按钮时,我才需要保持此行为。
我将如何实现它? 当用户点击一个 href 我正在使用一种方法来替换状态。然后页面被重定向到正确的位置。
window.history.replaceState({ scrollToProduct: true, productCode: 'produt-XXXX' }, document.title, `${window.location.href}?product-code=produt-XXXX`);
然后我试图在我的 App.vue 中注册 popstate 监听器
beforeMount() {
window.onpopstate = function(e) {
console.log(e);
};
}
我的问题在哪里? 不幸的是,popstate 监听器没有附加,所以我无法捕捉到“返回”按钮的点击。
我也尝试过使用 router.push。
this.$router.push({ name: 'NameOfComponent' });
有趣的是,我被导航到另一个页面(无需重新加载页面),当我单击后退按钮时,popstate 确实有效。不幸的是,我无法将任何东西传递到历史状态。
有人可以帮忙吗?
PS:我没有使用SPA,而是在每个页面上刷新。
【问题讨论】:
标签: javascript vue.js vue-router browser-history