index.vue 2.71 KB
<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>