项目中需要实现一个可拖拽窗口的效果,这里使用插槽的方式实现效果
<template>
<transition class="move_root">
<!-- 绑定style中top和left-->
<div class="moveBox" :style="position" v-show="show">
<div class="moveHead" @mousedown="mousedown" @mousemove="mousemove" @mouseup="mouseup" @mouseleave="mousemove">{{ title }}</div>
<!-- 关闭按钮-->
<div class="close" @click="toggleShow()">×</div>
<div class="content">
<!--插槽-->
<slot></slot>
</div>
</div>
</transition>
</template>
逻辑代码
<script>
export default {
name: 'moveBox',
props: ['title'],
data() {
return {
show: true, //是否显示
x: 100, //left:x
y: 50, //top:y
leftOffset: 0, //鼠标距离移动窗口左侧偏移量
topOffset: 0, //鼠标距离移动窗口顶部偏移量
isMove: false, //是否移动标识
}
},
computed: {
//top与left加上px
position() {
return `top:${this.y}px;left:${this.x}px;`
},
},
methods: {
//控制打开关闭
toggleShow(data) {
this.x = 100
this.y = 50
this.show = !this.show
},
mousedown(event) {
//鼠标按下事件
this.leftOffset = event.offsetX
this.topOffset = event.offsetY
this.isMove = true
},
//鼠标移动
mousemove(event) {
if (!this.isMove) {
return
}
this.x = event.clientX - this.leftOffset
this.y = event.clientY - this.topOffset
},
//鼠标抬起
mouseup() {
this.isMove = false
},
},
}
</script>
css样式
<style lang="less" scoped>
.moveBox {
width: 500px;
// height: 300px;
position: fixed;
z-index: 99998;
background: rgb(255, 255, 255);
box-shadow: 0 0 5px 3px #95a5a6;
.moveHead {
height: 35px;
background-color: #e63e31;
cursor: move;
color: #fff;
padding: 9px 0 0 11px;
}
.close {
position: absolute;
right: 0;
top: 0;
line-height: 30px;
font-size: 24px;
cursor: pointer;
display: block;
width: 30px;
height: 30px;
text-align: center;
}
}
.v-enter,
.v-leave-to {
opacity: 0;
transform: scale(0.5);
}
.content {
padding: 10px;
}
.v-enter-active,
.v-leave-active {
transition: all 0.5s ease;
}
</style>