需求:当左侧菜单栏内菜单项较多时,刷新页面时要求左侧菜单导航栏滚动到当前菜单项目位置;路由发生跳转时同上
所用到的API:
1.scrollIntoView
2.IntersectionObserver
具体代码实现:
onMounted(async () => {
scrollActiveMenuToView()
})
watch(() => route.path, () => {
scrollActiveMenuToView("smooth")
})
const scrollActiveMenuToView = async (behavior: ScrollBehavior = 'auto') => {
await nextTick()
const scroller = document.querySelector('.sidebar-scrollbar') as HTMLElement
const activeMenu = scroller.querySelector('.el-sub-menu.is-active')
if (activeMenu) {
const intersectionObserver = new IntersectionObserver((entries) => {
if (!entries[0].isIntersecting) {
activeMenu.scrollIntoView({ block: 'end', behavior })
} else {
intersectionObserver.disconnect()
}
}, {
root: scroller, //被监听的滚动盒子
threshold: 1 //entries[0].isIntersecting的阈值-此处表示当前菜单项完全出现
})
intersectionObserver.observe(activeMenu)
}
}