1. 组件:Resize
<template>
<div :style="{width: defaultWidth + 'px', position: 'relative'}">
<div ref="container" class="d-flex">
<div style="width: 100%; height: 100vh;">
<!-- 显示内容主体-->
<slot name="body"></slot>
</div>
</div>
<!-- 拖拽条 -->
<div v-if="resizeShow" class="resize" @mousedown.stop="onMouseDown" @mouseup.stop="onMouseup"/>
</div>
</template>
<script>
export default {
props: {
resizeShow: {
type: Boolean,
default: true
}
},
data() {
return {
defaultWidth: 240,
beforeWidth: 0,
afterWidth: 0
}
},
methods: {
onMouseDown(e) {
this.beforeWidth = e.clientX
document.addEventListener('mousemove', this.onMousemove)
document.addEventListener('mouseup', this.onMouseup)
e.preventDefault()
},
onMousemove(e) {
this.afterWidth = e.clientX
if (this.beforeWidth < this.afterWidth) {
this.defaultWidth = this.defaultWidth + (this.afterWidth - this.beforeWidth)
this.beforeWidth = e.clientX
} else {
this.defaultWidth = this.defaultWidth - (this.beforeWidth - this.afterWidth)
this.beforeWidth = e.clientX
}
},
onMouseup(e) {
e.preventDefault()
document.removeEventListener('mousedown', this.onMouseDown)
document.removeEventListener('mousemove', this.onMousemove)
}
}
}
</script>
<style>
.d-flex {
display: inline-block;
overflow: hidden;
width: 100%;
}
.resize {
position: absolute;
top: 0;
right: 1px;
display: inline-block;
width: 20px;
height: 100%;
cursor: col-resize;
margin: 0 1px;
}
</style>
2. JavaScript调用组件
<template>
<div class="app-box">
<ResizeBox :resizeShow="resizeShow"/>
</div>
</template>
<script>
import ResizeBox from './components/ResizeBox/index.vue';
export default {
data(){
return{
resizeShow:true
}
},
components:{
ResizeBox
}
}
</script>
<style scoped>
.app-box {
display: flex;
}
</style>
3. TypeScript调用组件
<template>
<div class="app-box">
<ResizeBox :resizeShow="resizeShow"/>
</div>
</template>
<script setup lang="ts">
import ResizeBox from './components/ResizeBox/index.vue';
let resizeShow = true;
</script>
<style scoped>
.app-box {
display: flex;
}
</style>