Click the button on the vue page to copy text

Create a new util.js file

export const copyToClipboard = (text, callback) => {
	if (navigator.clipboard) {
		// clipboard api 复制
		navigator.clipboard.writeText(text);
	} else {
		var textarea = document.createElement("textarea");
		document.body.appendChild(textarea);
		// 隐藏此输入框
		textarea.style.position = "fixed";
		textarea.style.clip = "rect(0 0 0 0)";
		textarea.style.top = "10px";
		// 赋值
		textarea.value = text;
		// 选中
		textarea.select();
		// 复制
		document.execCommand("copy", true);
		// 移除输入框
		document.body.removeChild(textarea);
	}
  if(callback) callback(text)
};

Page usage

Introduce import { copyToClipboard } from "../../utils/util";

Pass in the parameters to be copied, such as mobile phone number

      copyToClipboard("180****5313", () => {
        this.$message.success("手机号复制成功");
      });

Guess you like

Origin blog.csdn.net/weixin_57163112/article/details/128455074