index_slot.vue 2.39 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"
    />
    <div v-show="visible" class="contextmenu" :style="{ left: left + 'px', top: top + 'px' }">
      <slot />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref, watch } from 'vue'

const { proxy } = getCurrentInstance()
const emit = defineEmits(['node-click', 'node-contextmenu'])

const props = defineProps({
  data: {
    type: Array
  },
  props: {
    type: Object,
    default: () => {
      return {
        value: 'id', // ID字段名
        label: 'label', // 显示名称
        children: 'children' // 子级字段名
      }
    }
  },
  defaultExpandAll: {
    type: Boolean,
    default: true
  }
})
const visible = ref(false)
const top = ref(0)
const left = ref(0)

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

  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
}

</script>

<style lang="scss">
.contextmenu {
  margin: 0;
  z-index: 3000;
  position: absolute;

  ul {
    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>