index.vue
1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<template>
<ul v-show="visible" class="contextmenu" :style="{ left: left + 'px', top: top + 'px' }">
<li v-for="item in props.menu" :key="item.name" @click="menuClick(item)">
<el-icon v-if="item.icon">
<component :is="item.icon" />
</el-icon>
{{ item.name }}
</li>
</ul>
</template>
<script setup>
import { nextTick, ref, watch } from 'vue'
import { getCurrentInstance } from '@vue/runtime-core'
import { useWindowSize } from '@vueuse/core'
const emit = defineEmits(['menu-click'])
const { proxy } = getCurrentInstance()
const { width, height } = useWindowSize()
const props = defineProps({
menu: {
type: Array,
default: () => []
}
})
const visible = ref(false)
const top = ref(0)
const left = ref(0)
function menuClick(item) {
emit('menu-click', item)
}
function open(e) {
visible.value = true
top.value = 0
left.value = 0
nextTick(() => {
const offset = proxy.$el.getBoundingClientRect()
const l = e.clientX - offset.left + 5
const t = e.clientY - offset.top - 5
const maxLeft = width.value - offset.left - offset.width
const maxTop = height.value - offset.top - offset.height
left.value = Math.min(l, maxLeft)
top.value = Math.min(t, maxTop)
})
}
watch(visible, (value) => {
if (value) {
document.body.addEventListener('click', closeMenu)
} else {
document.body.removeEventListener('click', closeMenu)
}
})
function closeMenu() {
visible.value = false
}
defineExpose({
open,
close: closeMenu
})
</script>
<style scoped lang="scss">
.contextmenu {
margin: 0;
z-index: 3000;
position: absolute;
background: #fff;
list-style-type: none;
padding: 5px 0;
border-radius: 4px;
font-size: 12px;
font-weight: 400;
color: #333;
box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
li {
margin: 0;
padding: 7px 16px;
cursor: pointer;
&:hover {
background: #eee;
}
}
}
</style>