diff --git a/vdoing/components/RightMenu.vue b/vdoing/components/RightMenu.vue index 941165dd..8146dfb0 100644 --- a/vdoing/components/RightMenu.vue +++ b/vdoing/components/RightMenu.vue @@ -8,6 +8,7 @@ 'level' + item.level, { active: item.slug === hashText }, ]" + :id="`${item.slug}-slug`" v-for="(item, i) in headers" :key="i" > @@ -86,6 +87,8 @@ export default { $route() { this.headers = getNewHeaders(this.$page.headers); this.getHashText(); + // 滚动到指定位置 + this.scrollToHash(); }, }, methods: { @@ -98,6 +101,11 @@ export default { this.hashText = this.headers[0]?.slug; } }, + scrollToHash() { + const element = document.getElementById(`${this.hashText}-slug`); + if (element) + element.scrollIntoView({ behavior: "smooth", block: "center" }); + }, }, }; diff --git a/vdoing/layouts/Layout.vue b/vdoing/layouts/Layout.vue index d2643437..b00a48db 100644 --- a/vdoing/layouts/Layout.vue +++ b/vdoing/layouts/Layout.vue @@ -234,13 +234,7 @@ export default { }, mounted() { init(); - // 初始化页面时链接锚点无法跳转到指定id的解决方案 - const hash = document.location.hash; - if (hash.length > 1) { - const id = decodeURIComponent(hash.substring(1)); - const element = document.getElementById(id); - if (element) element.scrollIntoView(); - } + this.initView(); // 解决移动端初始化页面时侧边栏闪现的问题 this.showSidebar = true; @@ -281,8 +275,22 @@ export default { themeMode() { this.setBodyClass(); }, + "$route.path"() { + setTimeout(() => { + this.initView(); + }, 100); + }, }, methods: { + initView() { + // 初始化页面时链接锚点无法跳转到指定id的解决方案 + const hash = document.location.hash; + if (hash.length > 1) { + const id = decodeURIComponent(hash.substring(1)); + const element = document.getElementById(id); + if (element) element.scrollIntoView({ behavior: "smooth" }); + } + }, getHtmlStr(module) { const { htmlModules } = this.$themeConfig; return htmlModules ? htmlModules[module] : "";