<template>
<div class="tree">
<span
class="tree-item"
v-for="(item, index) in tree"
:key="index"
@contextmenu.prevent="openMenu(item, $event)">
{{ item.name }}
</span>
<div class="popover" :style="style" v-if="isShowPopover">
<div v-for="(item, index) in popoverList" :key="index" class="popover-item" @click="menuClick(item)">
<i :class="'el-icon-' + item.type"></i>
{{ item.name }}
</div>
</div>
</div>
</template>
<script>
export default {
name: 'NotFound',
computed: {
// 计算出距离
style () {
return {
left: this.popoverLeft + 'px',
top: this.popoverTop + 'px'
}
}
},
data () {
return {
tree: [
{ name: '一级1' },
{ name: '一级2' }
],
popoverLeft: 0, // 距离左边的距离
popoverTop: 0, // 距离顶部的距离
isShowPopover: true, // 是否展示右键内容
popoverList: [
{ name: '新增', type: 'circle-plus-outline' },
{ name: '编辑', type: 'edit' },
{ name: '删除', type: 'delete' }
]
}
},
methods: {
// 展开菜单
openMenu (item, event, index) {
this.curItem = item
this.curIndex = index
// 判断窗口大小
const clientWidth = document.body.clientWidth
const clientHeight = document.body.clientHeight
// 鼠标右键边界值判断(100,178是右键菜单的宽高)
if (event.clientX + 100 >= clientWidth) {
this.popoverLeft = clientWidth - 100
} else {
this.popoverLeft = event.clientX
}
if (event.clientY + 178 >= clientHeight) {
this.popoverTop = clientHeight - 178
} else {
this.popoverTop = event.clientY
}
this.isShowPopover = true // 显示自定义菜单栏
},
// 关闭菜单
closeMenu () {
this.isShowPopover = false
},
// 菜单某一项被点击
menuClick (row) {
console.log(row)
}
},
watch: {
// 目的: 为了在鼠标右键内容展示,点击其他地方隐藏鼠标右键内容
isShowPopover (val) {
if (val) {
document.body.addEventListener('click', this.closeMenu)
} else {
document.body.removeEventListener('click', this.closeMenu)
}
}
}
}
</script>
<style lang="scss" scoped>
.tree {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.tree-item {
width: 200px;
line-height: 40px;
border: 1px solid red;
text-align: center;
margin-top: 10px;
cursor: pointer;
}
.popover {
width: 100px;
height: auto;
position: fixed;
background: #fff;
border: 1px solid #ddd;
padding: 0 10px;
box-shadow: 0 0 2px 0 #ccc;
.popover-item {
border-bottom: 1px solid #efefef;
line-height: 35px;
text-align: center;
cursor: pointer;
}
.popover-item:last-child{
border-bottom: none;
}
}
}
</style>
自定义右键菜单
最新推荐文章于 2024-03-31 17:57:22 发布