Vue3 自定义指令 右键copy 命令

274 阅读1分钟
export default {
  mounted(el) {
    el.addEventListener("contextmenu", (event) => {
      event.preventDefault();

      // 创建自定义菜单
      const menu = document.createElement("div");
      menu.style.position = "fixed";
      menu.style.top = `${event.clientY}px`;
      menu.style.left = `${event.clientX}px`;
      menu.style.backgroundColor = "#fff";
      menu.style.border = "1px solid #ccc";
      menu.style.padding = "5px";
      menu.style.zIndex = "100000";
      menu.style.cursor = "pointer";
      menu.innerText = "复制文本";

      // 添加点击事件来复制文本
      menu.addEventListener("click", () => {
        const range = document.createRange();
        range.selectNodeContents(el);
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);

        try {
          document.execCommand("copy");
          alert("文本已复制");
        } catch (err) {
          alert("复制失败");
        }

        // 移除菜单
        document.body.removeChild(menu);
      });

      // 移除之前的菜单
      const existingMenu = document.getElementById("custom-context-menu");
      if (existingMenu) {
        document.body.removeChild(existingMenu);
      }

      // 给菜单设置一个 id,以便后续移除
      menu.id = "custom-context-menu";

      // 添加菜单到 body
      document.body.appendChild(menu);

      // 点击其他地方时移除菜单
      document.addEventListener(
        "click",
        () => {
          if (document.body.contains(menu)) {
            document.body.removeChild(menu);
          }
        },
        { once: true }
      );
    });
  },
  unmounted(el) {
    // 清理事件监听器
    el.removeEventListener("contextmenu", this.contextMenuHandler);
  },
};
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import copyOnRightClick from './directives/copyOnRightClick';
const app = createApp(App);
app.directive('copy-on-right-click', copyOnRightClick);
app.use(ElementPlus);
app.use(store);
app.use(router);
app.mount("#app");