Skip to content

Commit 5918ca9

Browse files
committed
feat: better hash locate behavior
1 parent 62a92fc commit 5918ca9

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

packages/@vuepress/core/lib/app/root-mixins/updateLoadingState.js

+26-1
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,36 @@ export default {
22
created () {
33
this.$vuepress.$on('AsyncMarkdownContentMounted', () => {
44
this.$vuepress.$set('contentMounted', true)
5+
6+
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
7+
anchor.addEventListener('click', function (e) {
8+
e.preventDefault()
9+
window.scroll({
10+
top: e.target.offsetTop - 75,
11+
left: 0,
12+
behavior: 'smooth'
13+
})
14+
})
15+
})
16+
17+
if (this.$route.hash) {
18+
try {
19+
const anchor = document.getElementById(this.$route.hash.slice(1))
20+
const anchorLink = anchor.querySelector('a.header-anchor')
21+
window.scroll({
22+
top: anchorLink.offsetTop - 70,
23+
left: 0,
24+
behavior: 'auto'
25+
})
26+
} catch (e) {
27+
console.error(e)
28+
}
29+
}
530
})
631
},
732

833
watch: {
9-
$page () {
34+
'$route.path' () {
1035
this.$vuepress.$set('contentMounted', false)
1136
}
1237
}

packages/@vuepress/plugin-active-header-links/mixin.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,21 @@ function getAnchors () {
4141
})
4242
}
4343

44+
let freezeScrollEvent = false
45+
4446
export default {
47+
watch: {
48+
'$route.path' () {
49+
console.log('$route.path changed')
50+
freezeScrollEvent = true
51+
}
52+
},
53+
4554
mounted () {
4655
this.$vuepress.$on('AsyncMarkdownContentMounted', (slotKey) => {
56+
freezeScrollEvent = false
4757
if (slotKey === 'default') {
48-
window.addEventListener('scroll', this.onScroll)
58+
window.addEventListener('scroll', () => this.onScroll(freezeScrollEvent))
4959
}
5060
})
5161

@@ -66,7 +76,10 @@ export default {
6676
},
6777

6878
methods: {
69-
onScroll: throttle(function () {
79+
onScroll: throttle(function (freezeScrollEvent) {
80+
if (freezeScrollEvent) {
81+
return
82+
}
7083
const anchors = getAnchors()
7184
if (anchors.length === 0) {
7285
return

0 commit comments

Comments
 (0)