You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中TypeScript转Composition API(setup)右键菜单报错求助

解决Vue3
**注意事项**:
- `getCurrentInstance`仅能在组件的setup函数或同步生命周期钩子中使用,不能在异步回调(如`setTimeout`)中调用。
- 使用可选链`?.`可以避免实例为`null`(如SSR场景)时的报错。

### 方案2:直接使用库提供的调用函数(推荐)
如果你的右键菜单是通过第三方库实现的,很多库会提供直接调用的函数,无需挂载到全局。例如部分右键菜单库会导出`showContextMenu`之类的方法,直接导入使用即可:

```vue
<template>
    <div style="width:300px;height:300px;background:red;" @contextmenu="onContextMenu1($event)" >
        Right Mouse Click Here
    </div>
</template>

<script lang="ts" setup>
import { showContextMenu } from '你的右键菜单库路径';
import { MenuOptions } from '../../src/ContextMenuDefine';

const onContextMenu1 = (e: MouseEvent) => {
    e.preventDefault();
    
    showContextMenu({
        items: [
          { 
            label: 'This is menu in parent box',
          },
          { 
            label: 'Simple item',
          },
        ],
        iconFontClass: 'iconfont',
        customClass: "class-a",
        zIndex: 3,
        minWidth: 230,
        x: e.x,
        y: e.y
      } as MenuOptions);
}
</script>

这种方式比依赖全局属性更清晰,也符合Vue3的组合式API风格。

内容的提问来源于stack exchange,提问作者Harnsle Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:25:55