核心在于监听鼠标的move来改变div的高度,抽成了组件
<template>
<div ref="container" class="drag">
<z-tooltip v-if="isShowIcon" effect="dark" content="格式化" placement="top-start">
<div @click="handleClick">
<c-icon icon-class="TextFormatwenbengeshi10" class-name="code-icon"></c-icon>
</div>
</z-tooltip>
<div class="bottom" :style="{ height: bottomHeight + 'px' }">
<slot name="content"></slot>
</div>
<div ref="top" v-draggable class="top"></div>
</div>
</template>
<script>
export default {
name: 'Drag',
directives: {
draggable: {
inserted(el) {
el.style.cursor = 'ns-resize'
}
}
},
props: {
minHeight: {
type: Number,
default: 85
},
maxHeight: {
type: Number,
default: 600
},
height: {
type: Number,
default: 85
},
isShowIcon: {
type: Boolean,
default: false
}
},
data() {
return {
bottomHeight: 85 // 初始化底部div的高度
}
},
watch: {
height: {
handler(val) {
this.bottomHeight = val
this.instance?.layout()
},
immediate: true,
deep: true
}
},
mounted() {
this.dragControllerDiv()
},
methods: {
dragControllerDiv() {
const containerDiv = this.$refs.container
const topDiv = this.$refs.top
let startMouseY
let startContainerHeight
const mouseMoveHandler = e => {
e.preventDefault()
// 计算拖动距离
const deltaY = e.clientY - startMouseY
// 计算新的容器高度
const newContainerHeight = startContainerHeight + deltaY
// 高度限制
const clampedHeight = Math.max(this.minHeight, Math.min(this.maxHeight, newContainerHeight))
// 计算底部div的高度
const newBottomHeight = clampedHeight - topDiv.offsetHeight
this.$emit('move', newBottomHeight)
// 更新底部div的高度
this.bottomHeight = newBottomHeight
}
const mouseUpHandler = () => {
document.removeEventListener('mousemove', mouseMoveHandler)
document.removeEventListener('mouseup', mouseUpHandler)
}
topDiv.addEventListener('mousedown', e => {
e.preventDefault()
startMouseY = e.clientY
startContainerHeight = containerDiv.offsetHeight + 10
document.addEventListener('mousemove', mouseMoveHandler)
document.addEventListener('mouseup', mouseUpHandler)
})
},
handleClick() {
console.log('121')
this.$emit('up')
}
}
}
</script>
<style>
/* 拖拽相关样式 */
.drag {
position: relative;
width: 100%;
}
.top {
position: absolute;
bottom: 0;
height: 2px;
cursor: ns-resize;
background-color: rgb(187 187 187);
z-index: 100;
width: calc(100% - 10px);
left: 11px;
&:hover {
background-color: #3693ff;
height: 3px;
}
}
.bottom {
height: auto;
background-color: #fff;
z-index: 100;
width: 100%;
overflow: hidden;
}
.code-icon {
float: right;
cursor: pointer;
}
</style>