vue3自定义指令,点击复制,并修改粘贴板的值以及和vue2的区别

发布于 2023-12-16  93 次阅读


自定义指令

@/drective/index.ts

const tocolor = {
  beforeMount(el: { style: { color: any } }, binding: { value: any }) {
    el.style.color = binding.value;
  },
};

const mycopy = {
  beforeMount(el, binding) {
    el.targetContent = binding.value;
    el.addEventListener("click", () => {
      if (!el.targetContent) return console.warn("没有需要复制的目标内容");
      // 创建textarea标签
      const textarea = document.createElement("textarea");
      // 设置相关属性
      textarea.readOnly = "readonly";
      textarea.style.position = "fixed";
      textarea.style.top = "-99999px";
      // 把目标内容赋值给它的value属性
      textarea.value = "复制成功,剪贴板内容:" + el.targetContent;
      // 插入到页面
      document.body.appendChild(textarea);
      // 调用onselect()方法
      textarea.select();
      // 把目标内容复制进剪贴板, 该API会返回一个Boolean
      try {
        // 复制文本到剪贴板
        var successful = document.execCommand('copy');
        if (successful) {
            console.log('成功复制到剪贴板!');
        } else {
            console.error('无法复制到剪贴板!');
        }
    } catch (err) {
        console.error('无法复制到剪贴板!', err);
    }      // 移除textarea标签
      document.body.removeChild(textarea);
    });
  },
  updated(el, binding) {
    // 实时更新最新的目标内容
    el.targetContent = binding.value;
  },
  unmounted(el) {
    el.removeEventListener("click", () => {});
  },
};
export { tocolor, mycopy };

main.ts

const app = createApp(App);
import {tocolor,mycopy} from "@/directive/index.ts"

app.directive('tocolor',tocolor)
app.directive('mycopy',mycopy)
app.use(store).use(router).mount("#app");
使用
 <div v-mycopy="nomol">
      点击复制
    </div>

和vue2自定义的指令的区别

1、时间节点不同

Vue3 Vue2
created
beforeMount bind
mounted inserted
beforeUpdate update
updated componentUpdated
beforeUnmount
unmounted unbind

2、使用不同

vue2中自定义指令

Vue.directive('focus', {
  bind() {},
  inserted(el) {
    el.focus()
  },
  update() {},
  componentUpdated() {},
  unbind() {}
})

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。