vue 右键菜单的实现

最近一个项目,选中某些文本,然后右键进行一些操作,使用了vue-contextmenujs插件

  1. 安装vue-contextmenujs

    npm install vue-contextmenujs

  2. mian.js中引用该组件

    import Contextmenu from 'vue-contextmenujs';
    Vue.use(Contextmenu);

  3. 页面中使用

4.判断是否在该文本区域内

复制代码
 rightClick(event) {
      console.log("点击了右键", event);
      this.chapterText = ""; // 先清空,chapterText 保存选中文本
      let sel = window.getSelection
        ? window.getSelection()
        : document.selection.createRange();
      let text = sel.toString();
      if (!text) {
        return false;
      }

      let divId = "bodyContainer";
      if (sel.getRangeAt) {

        var range = sel.getRangeAt(0);
        var ancestor = range.commonAncestorContainer;
        while (
          ancestor.id != divId && // Check id, class or otherwise
          ancestor.parentElement != null
        ) {
          ancestor = ancestor.parentElement;
        }

        if (ancestor.id == divId) {
          // Selection is within the editor.
          console.log("在div内");
          this.chapterText = window.getSelection().toString();
          this.$contextmenu({
            items: this.rightMenuData,
            event, // 鼠标事件信息
            customClass: "custom-class", // 自定义菜单 class
            zIndex: 3, // 菜单样式 z-index
            minWidth: 150, // 主菜单最小宽度
          });
        } else {
          console.log("不在div内");
          return false;
        }
      } else {
        //
        return false;
      }

      return false;
    },

5.菜单

复制代码
 rightMenuData: [
        {
          label: "翻译",
          onClick: () => {
            this.handleTranslate();
          },
        },
           ....
        },
      ],
相关推荐
北辰alk11 小时前
Vue 动态路由完全指南:定义与参数获取详解
vue.js
北辰alk11 小时前
Vue Router 完全指南:作用与组件详解
vue.js
北辰alk11 小时前
Vue 中使用 this 的完整指南与注意事项
vue.js
xkxnq11 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
北辰alk11 小时前
Vue 插槽(Slot)完全指南:组件内容分发的艺术
vue.js
烛阴11 小时前
拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境
前端·webgl·three.js
北辰alk11 小时前
Vue 组件中访问根实例的完整指南
vue.js
Van_Moonlight11 小时前
RN for OpenHarmony 实战 TodoList 项目:空状态占位图
javascript·开源·harmonyos
北辰alk11 小时前
Vue Router 中获取路由参数的全面指南
vue.js
北辰alk11 小时前
Vue 的 v-cloak 和 v-pre 指令详解
vue.js