分享记录vue3+ts的超简单且通俗易懂的右键菜单。
<template>
<div id="app">
<div
class="context-menu"
:style="{ top: top + 'px', left: left + 'px', display: display }"
>
<ul>
<li @click="handleClick('选项1')">选项1</li>
<li @click="handleClick('选项2')">选项2</li>
<li @click="handleClick('其他')">其他</li>
</ul>
</div>
<div id="content" @contextmenu.prevent="openMenu">
右键点击这里查看菜单
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const top = ref(0);
const left = ref(0);
const display = ref('none');
const openMenu = (event: MouseEvent) => {
top.value = event.clientY;
left.value = event.clientX;
display.value = 'block';
};
const handleClick = (action: string) => {
alert(`你选择了: ${action}`);
display.value = 'none';
};
return { top, left, display, openMenu, handleClick };
}
});
</script>
<style>
#content {
width: 200px;
height: 200px;
border: 1px solid #000;
margin: 20px;
}
.context-menu {
position: absolute;
background-color: #fff;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
user-select: none;
z-index: 1000;
}
.context-menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.context-menu li {
padding: 8px 12px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.context-menu li:last-child {
border-bottom: none;
}
.context-menu li:hover {
background-color: #f0f0f0;
}
</style>
这段代码展示了如何在Vue 3和TypeScript中创建一个基本的右键菜单。用户在指定区域右键点击时,会打开一个上下文菜单,并可以选择不同的选项。选择某个选项后,会通过弹窗显示选择,并关闭菜单。这个例子简单易懂,适合新手学习和实践。
评论已关闭