Skip to content

Commit d2ea14b

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

File tree

2 files changed

+43
-3
lines changed

2 files changed

+43
-3
lines changed

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

+28-1
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,38 @@ 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+
console.log(e)
9+
e.preventDefault()
10+
window.scroll({
11+
top: e.target.offsetTop - 75,
12+
left: 0,
13+
behavior: 'smooth'
14+
})
15+
})
16+
})
17+
18+
if (this.$route.hash) {
19+
try {
20+
const anchor = document.getElementById(this.$route.hash.slice(1))
21+
const anchorLink = anchor.querySelector('a.header-anchor')
22+
console.log(anchorLink.offsetTop - 70)
23+
window.scroll({
24+
top: anchorLink.offsetTop - 70,
25+
left: 0,
26+
behavior: 'auto'
27+
})
28+
} catch (e) {
29+
console.error(e)
30+
}
31+
}
532
})
633
},
734

835
watch: {
9-
$page () {
36+
'$route.path' () {
1037
this.$vuepress.$set('contentMounted', false)
1138
}
1239
}

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)