Skip to content

Commit

Permalink
feat: better hash locate behavior
Browse files Browse the repository at this point in the history
  • Loading branch information
ulivz committed Nov 7, 2018
1 parent 62a92fc commit 5918ca9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,36 @@ export default {
created () {
this.$vuepress.$on('AsyncMarkdownContentMounted', () => {
this.$vuepress.$set('contentMounted', true)

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (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')
window.scroll({
top: anchorLink.offsetTop - 70,
left: 0,
behavior: 'auto'
})
} catch (e) {
console.error(e)
}
}
})
},

watch: {
$page () {
'$route.path' () {
this.$vuepress.$set('contentMounted', false)
}
}
Expand Down
17 changes: 15 additions & 2 deletions packages/@vuepress/plugin-active-header-links/mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
})

Expand All @@ -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
Expand Down

0 comments on commit 5918ca9

Please sign in to comment.