import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import piniaStore from "@/store";
import "@/assets/styles/index.scss"
import {useAccountInfoStore} from "@/store/accountInfoStore";
InitCustomConfig().then(config => {
const app = createApp(App)
.use(piniaStore)
.use(router)
.use(i18n)
document.title = config.logoConfig?.systemTitle ?? ""
// 自定义指令--拖拽
app.directive('drag',(el) => {
let oDiv = el // 当前元素
// let self = this // 上下文
// 禁止选择网页上的文字
document.onselectstart = function () {
return false
}
oDiv.onmousedown = function (e:any) {
oDiv.style.cursor = 'move'
let parentWidth = oDiv.parentElement.offsetWidth
let parentHeight = oDiv.parentElement.offsetHeight
let oDivWidth = oDiv.offsetWidth
let oDivHeight = oDiv.offsetHeight
// 鼠标按下,计算当前元素距离可视区的距离
let disX = e.clientX - oDiv.offsetLeft
let disY = e.clientY - oDiv.offsetTop
document.onmousemove = function (e) {
let left:number = e.clientX - disX
let top:number = e.clientY - disY
// 通过事件委托,计算移动的距离
if(left < 0) {
left = 0
}
if(top < 0) {
top = 0
}
if(left + oDivWidth > parentWidth) {
left = parentWidth - oDivWidth
}
if(top + oDivHeight > parentHeight) {
top = parentHeight - oDivHeight
}
let right = parentWidth - left - oDivWidth
let bottom = parentHeight - top - oDivHeight
//移动当前元素
oDiv.style.right = right + "px";
// oDiv.style.bottom = bottom + "px";
oDiv.style.top = top + "px";
}
document.onmouseup = function (e) {
oDiv.style.cursor = 'default'
document.onmousemove = null
document.onmouseup = null
}
// return false不加的话可能导致黏连,就是拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
return false
}
}
);
// 自定义指令--按钮权限
app.directive('permission',
(el, binding) => {
if (useAccountInfoStore().account.authority) {
if (useAccountInfoStore().account.authority?.indexOf(binding.value) === -1 && useAccountInfoStore().account.authority?.indexOf("admin") === -1) {
el.parentNode && el.parentNode.removeChild(el)
}
}
}
);
}).catch(err => {
console.log(err);
})
<template>
<div class="parents-box" v-drag >
<div class="sub-box">
可拖拽盒子
</div>
</div>
</template>
<script lang='ts' setup>
import { ref, reactive,watch } from 'vue'
import { $ref } from 'vue/macros';
</script>
<style scoped lang='scss'>
.parents-box {
width: 100%;
height: 100%;
position: relative;
.sub-box{
position: absolute;
right: 10px;
top: 10px;
width: 300px;
height: 200px;
user-select: none;
z-index: 2;
}
}
</style>
- 注意:
1.在定义自定义拖拽指令时设置 oDiv.style.right/oDiv.style.left oDiv.style.top/oDiv.style.bottom 的方向 在div元素上使用的时候css中的 right/left top/bottom 也需要保持一致 (要使用position: absolute;)
2.使用的div元素 css中 z-index需要设置的大一些 避免权重不够 拖拽时导致没有效果