提交 6b9b38b4 编写于 作者: U ULIVZ

feat($active-header-links): simplify implementation

上级 5b0cdcf5
...@@ -26,8 +26,7 @@ function calculateCurrentAnchor (anchors) { ...@@ -26,8 +26,7 @@ function calculateCurrentAnchor (anchors) {
return anchors[0] return anchors[0]
} }
function getAnchors () { function getAnchors (sidebarLinks) {
const sidebarLinks = [].slice.call(document.querySelectorAll(AHL_SIDEBAR_LINK_SELECTOR))
return [].slice return [].slice
.call(document.querySelectorAll(AHL_HEADER_ANCHOR_SELECTOR)) .call(document.querySelectorAll(AHL_HEADER_ANCHOR_SELECTOR))
.filter(anchor => sidebarLinks.some(sidebarLink => sidebarLink.hash === anchor.hash)) .filter(anchor => sidebarLinks.some(sidebarLink => sidebarLink.hash === anchor.hash))
...@@ -41,49 +40,23 @@ function getAnchors () { ...@@ -41,49 +40,23 @@ function getAnchors () {
}) })
} }
let freezeScrollEvent = true
export default { export default {
mounted () { mounted () {
this.$router.beforeEach((to, from, next) => {
if (to.path !== from.path) {
freezeScrollEvent = true
}
next()
})
this.$vuepress.$on('AsyncMarkdownContentMounted', (slotKey) => { this.$vuepress.$on('AsyncMarkdownContentMounted', (slotKey) => {
// delay activation of scroll event
setTimeout(() => {
freezeScrollEvent = false
}, 1000)
if (slotKey === 'default') { if (slotKey === 'default') {
window.addEventListener('scroll', () => this.onScroll(freezeScrollEvent)) window.addEventListener('scroll', this.onScroll)
} }
}) })
this.$vuepress.$on('AnchorHashChange', (anchor) => { this.$vuepress.$on('AnchorHashChange', (anchor) => {
// When user clicked sidebar links, we need to disable the scroll this.$router.replace(decodeURIComponent(anchor.hash))
// event triggered.
if (this.$route.hash === anchor.hash) {
return
}
this.$vuepress.$set('disableScrollBehavior', true)
this.$router.replace(decodeURIComponent(anchor.hash), () => {
// execute after scrollBehavior handler.
this.$nextTick(() => {
this.$vuepress.$set('disableScrollBehavior', false)
})
})
}) })
}, },
methods: { methods: {
onScroll: throttle(function (freezeScrollEvent) { onScroll: throttle(function () {
if (freezeScrollEvent) { this.$sidebarLinks = [].slice.call(document.querySelectorAll(AHL_SIDEBAR_LINK_SELECTOR))
return const anchors = getAnchors(this.$sidebarLinks)
}
const anchors = getAnchors()
if (anchors.length === 0) { if (anchors.length === 0) {
return return
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册