<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useMousePressed, useMouseInElement } from '@vueuse/core'
const containerRef = shallowRef()
const dividerRef = shallowRef()
const { pressed } = useMousePressed({ target: dividerRef, touch: false })
const { elementX } = useMouseInElement(containerRef)
const asideWidth = ref('300px')
watch(elementX, (newVal) => {
console.log(newVal, pressed.value)
if (!pressed.value) return
if (newVal < 300) {
asideWidth.value = '300px'
return
}
asideWidth.value = `${Math.floor(newVal)}px`
})
</script>
<template>
<ElContainer v-show="panel === 'tree'" ref="containerRef" class="container">
<ElAside class="aside"
></ElAside>
<div ref="dividerRef" class="divider"></div>
<ElMain class="main">
</ElMain>
</ElContainer>
<ElContainer v-show="panel === 'card'"> <BookCard :book="currentBook" /></ElContainer>
</template>
<style scoped lang="less">
.aside {
width: v-bind('asideWidth');
}
.divider {
flex: 0 0 4px;
&:hover {
background-color: var(--el-border-color);
cursor: col-resize;
}
&:active {
background-color: var(--el-border-color);
cursor: col-resize;
}
}
</style>
在flex容器(container)中横向排布侧边栏(aside)、分隔线(divider)和主要区域(main)通过useMousePressed获取分隔线上的鼠标按压状态,通过useMouseInElement获取容器内的鼠标移动状态,这些状态是响应式的侦听鼠标横向移动距离,仅当鼠标在分隔线按下(即拖拽)时,同步修改侧边栏宽度。
参考:流烨(链接:https://juejin.cn/post/7384242126429405225),相比调整了一下动态设置宽度的方式,改为width: v-bind(‘asideWidth’),同时,优化.divider的样式,增加hover,让它平时隐藏,鼠标滑过时显示更容易寻找。