javascript - 在刷新或手动 URL 更改时滚动到锚点
问题描述
我实现了这篇文章中的代码,在使用路由器导航时启用滚动锚点。
但我注意到,在刷新或手动导航(通过操作 URL)时,页面不会按预期滚动到锚点。
我可以将此代码添加到所有页面,它会起作用:
mounted() {
console.log('Location:', location.hash); //returns '#options'
console.log('Route:', this.$route.hash); //returns '#options'
if (location.hash)
this.$nextTick().then(() => this.$scrollTo(location.hash, 700));
}
是否有任何全局方法来设置此代码,而不必在每个页面中设置代码?
我试图在App.vue
文件上设置它,location.hash
道具返回正确的哈希,但this.$scrollTo()
说它找不到任何具有该 ID 的对象。
解决方案
我只是使用了vue-router
导航守卫:
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes,
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
this.app.$scrollTo(to.hash, 700);
return { selector: to.hash }
} else if (savedPosition) {
return savedPosition;
} else {
//When the route changes, the page should scroll back to the top.
this.app.$scrollTo('#app', 700);
return { x: 0, y: 0 }
}
}
});
router.afterEach((to, from) => {
if (to.hash && to.path != from.path)
Vue.nextTick().then(() => VueScrollTo.scrollTo(to.hash, 700));
});
与问题无关,但与带有哈希的导航有关:
如果您要在 中发布您的网站GitHub Pages
,则需要添加接下来的两个部分。
添加一个 404.html 静态页面,将导航重定向回根页面,但在sessionStorage
:
<script>
const segment = 1;
//Gets the relative path and the hash of the URL.
sessionStorage.redirect = '/' + location.pathname.slice(1).split('/').slice(segment).join('/');
sessionStorage.hash = location.hash;
//Forces the navigation back to the main page, since it's the only entry point that works.
location.replace(location.pathname.split('/').slice(0, 1 + segment).join('/'));
</script>
更改您的main.js
页面以期望重定向参数:
new Vue({
router,
i18n,
render: (h) => h(App),
created() {
//If a redirect exists, tell the router.
if (sessionStorage.redirect) {
const redirect = sessionStorage.redirect;
const hash = sessionStorage.hash;
delete sessionStorage.redirect;
delete sessionStorage.hash;
this.$router.push(redirect + hash);
}
}
}).$mount("#app");
推荐阅读
- javascript - 未捕获的 ReferenceError:未定义函数。jQuery 已附加
- python - Python - 如何按列表创建多个属性
- excel - 合并来自 600 多个 Excel 工作表和 1 个 Google 文档的数据
- visual-studio - 更正 SSIS 以随机顺序执行任务
- reactjs - 未找到模块:无法解析“@material-ui/core/AppBar”
- javascript - 获取后如何使用 FileReader 中的 readAsArrayBuffer 方法并获得正确的大小?
- ios - 新的 Swift 应用程序创建 Obj C 文件
- amazon-s3 - 检查是否存在 S3 密钥而不抛出异常
- adfs - 使用 ADFS 和 WAP 时未经身份验证的应用程序区域
- python - Python 3.x 未定义名称,@staticmethod,@classmethod 使用“打字”功能