diff --git a/packages/@vuepress/core/lib/app/root-mixins/updateLoadingState.js b/packages/@vuepress/core/lib/app/root-mixins/updateLoadingState.js index 4711e8d4da..cd26b1e170 100644 --- a/packages/@vuepress/core/lib/app/root-mixins/updateLoadingState.js +++ b/packages/@vuepress/core/lib/app/root-mixins/updateLoadingState.js @@ -2,11 +2,38 @@ export default { created () { this.$vuepress.$on('AsyncMarkdownContentMounted', () => { this.$vuepress.$set('contentMounted', true) + + document.querySelectorAll('a[href^="#"]').forEach(anchor => { + anchor.addEventListener('click', function (e) { + console.log(e) + e.preventDefault() + window.scroll({ + top: e.target.offsetTop - 75, + left: 0, + behavior: 'smooth' + }) + }) + }) + + if (this.$route.hash) { + try { + const anchor = document.getElementById(this.$route.hash.slice(1)) + const anchorLink = anchor.querySelector('a.header-anchor') + console.log(anchorLink.offsetTop - 70) + window.scroll({ + top: anchorLink.offsetTop - 70, + left: 0, + behavior: 'auto' + }) + } catch (e) { + console.error(e) + } + } }) }, watch: { - $page () { + '$route.path' () { this.$vuepress.$set('contentMounted', false) } } diff --git a/packages/@vuepress/plugin-active-header-links/mixin.js b/packages/@vuepress/plugin-active-header-links/mixin.js index 9868496985..1b3c7f8347 100644 --- a/packages/@vuepress/plugin-active-header-links/mixin.js +++ b/packages/@vuepress/plugin-active-header-links/mixin.js @@ -41,11 +41,21 @@ function getAnchors () { }) } +let freezeScrollEvent = false + export default { + watch: { + '$route.path' () { + console.log('$route.path changed') + freezeScrollEvent = true + } + }, + mounted () { this.$vuepress.$on('AsyncMarkdownContentMounted', (slotKey) => { + freezeScrollEvent = false if (slotKey === 'default') { - window.addEventListener('scroll', this.onScroll) + window.addEventListener('scroll', () => this.onScroll(freezeScrollEvent)) } }) @@ -66,7 +76,10 @@ export default { }, methods: { - onScroll: throttle(function () { + onScroll: throttle(function (freezeScrollEvent) { + if (freezeScrollEvent) { + return + } const anchors = getAnchors() if (anchors.length === 0) { return