index.vue
2.71 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<template>
<div style="position: relative">
<el-tree
ref="hyTreeRef"
:data="data"
:props="myProps"
:expand-on-click-node="false"
:default-expand-all="defaultExpandAll"
@node-click="handleNodeClick"
@node-contextmenu="handleNodeRightClick"
/>
<ul v-show="visible" class="contextmenu" :style="{ left: left + 'px', top: top + 'px' }">
<li v-for="item in rightMenu" :key="item.name" @click="menuClick(item)">
<el-icon v-if="item.icon">
<component :is="item.icon" />
</el-icon>
{{ item.name }}
</li>
</ul>
</div>
</template>
<script setup>
import { getCurrentInstance, ref, watch } from 'vue'
const { proxy } = getCurrentInstance()
const emit = defineEmits(['node-click', 'node-contextmenu', 'menu-click'])
const props = defineProps({
data: {
type: Array
},
props: {
type: Object,
default: () => {
return {
value: 'id', // ID字段名
label: 'label', // 显示名称
children: 'children' // 子级字段名
}
}
},
defaultExpandAll: {
type: Boolean,
default: true
},
rightMenu: {
type: Array
}
})
const visible = ref(false)
const top = ref(0)
const left = ref(0)
const selectedNode = ref({})
const myProps = ref({})
watch(() => props.props, (val) => {
myProps.value = val
}, { immediate: true })
/** 节点单击事件 */
function handleNodeClick(node) {
closeMenu()
emit('node-click', node)
}
/**
* 节点右击
*/
function handleNodeRightClick(event, node) {
const menuMinWidth = 105
const offsetLeft = proxy.$el.getBoundingClientRect().left // container margin left
const offsetTop = proxy.$el.getBoundingClientRect().top
const offsetWidth = proxy.$el.offsetWidth // container width
const maxLeft = offsetWidth - menuMinWidth // left boundary
const l = event.clientX - offsetLeft + 10
left.value = Math.min(l, maxLeft)
top.value = event.clientY - offsetTop - 28
visible.value = true
selectedNode.value = node
emit('node-contextmenu', node)
}
watch(visible, (value) => {
if (value) {
document.body.addEventListener('click', closeMenu)
} else {
document.body.removeEventListener('click', closeMenu)
}
})
function closeMenu() {
visible.value = false
}
function menuClick(item) {
emit('menu-click', item, selectedNode.value)
}
</script>
<style 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>