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