Skip to content

Commit

Permalink
fix(theme-default): access dom after mounted (#895)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope committed May 15, 2022
1 parent ea53747 commit 68be74d
Showing 1 changed file with 34 additions and 31 deletions.
@@ -1,46 +1,49 @@
<script setup lang="ts">
import SidebarItem from '@theme/SidebarItem.vue'
import { watch } from 'vue'
import { onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useSidebarItems } from '../composables'
const route = useRoute()
const sidebarItems = useSidebarItems()
watch(
() => route.hash,
(hash) => {
// get the sidebar DOM
const sidebar = document.querySelector('.sidebar')
if (!sidebar) return
onMounted(() => {
watch(
() => route.hash,
(hash) => {
// get the sidebar DOM
const sidebar = document.querySelector('.sidebar')
if (!sidebar) return
// get the active sidebar item DOM, whose href equals to the current route
const activeSidebarItem = document.querySelector(
`.sidebar a.sidebar-item[href="${route.path}${hash}"]`
)
if (!activeSidebarItem) return
// get the active sidebar item DOM, whose href equals to the current route
const activeSidebarItem = document.querySelector(
`.sidebar a.sidebar-item[href="${route.path}${hash}"]`
)
if (!activeSidebarItem) return
// get the top and height of the sidebar
const sidebarTop = sidebar.getBoundingClientRect().top
const sidebarHeight = sidebar.getBoundingClientRect().height
// get the top and height of the sidebar
const { top: sidebarTop, height: sidebarHeight } =
sidebar.getBoundingClientRect()
// get the top and height of the active sidebar item
const { top: activeSidebarItemTop, height: activeSidebarItemHeight } =
activeSidebarItem.getBoundingClientRect()
// get the top and height of the active sidebar item
const activeSidebarItemTop = activeSidebarItem.getBoundingClientRect().top
const activeSidebarItemHeight =
activeSidebarItem.getBoundingClientRect().height
if (activeSidebarItemTop < sidebarTop) {
// scroll to the top edge of sidebar when the active sidebar item overflows the top edge of sidebar
activeSidebarItem.scrollIntoView(true)
} else if (
activeSidebarItemTop + activeSidebarItemHeight >
sidebarTop + sidebarHeight
) {
// scroll to the bottom edge of sidebar when the active sidebar item overflows the bottom edge of sidebar
activeSidebarItem.scrollIntoView(false)
// when the active sidebar item overflows the top edge of sidebar
if (activeSidebarItemTop < sidebarTop) {
// scroll to the top edge of sidebar
activeSidebarItem.scrollIntoView(true)
}
// when the active sidebar item overflows the bottom edge of sidebar
else if (
activeSidebarItemTop + activeSidebarItemHeight >
sidebarTop + sidebarHeight
) {
// scroll to the bottom edge of sidebar
activeSidebarItem.scrollIntoView(false)
}
}
}
)
)
})
</script>

<template>
Expand Down

0 comments on commit 68be74d

Please sign in to comment.