likes
comments
collection
share

VUE、JS实现复制文本

作者站长头像
站长
· 阅读数 26

一、前言

适用场景:

  • 复制文本
  • 复制链接
  • 复制段落
  • 复制账号、手机号
  • ···

二、实现方法

1、clipboard API

  • 剪贴板 clipboard API 提供了响应剪贴板命令(剪切、复制和粘贴)与异步读写系统剪贴板的能力;
  • 本次仅演示复制文本,其他Api可自行探索。
<template>
  <div class="box">
    <button style="margin: 20px" class="copy" @click="copy(data.text)">复制</button>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, watch, computed, defineProps } from "vue";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const store = useStore();
const data = reactive({
  text:'这是一段内容'
});
// 复制
const copy = (txt) => {
  // navigator clipboard 需要https等安全上下文
	if (navigator.clipboard && window.isSecureContext) {
		// 写入复制内容
		navigator.clipboard.writeText(val)
		// 提示
		// return ElMessage({
		// 	message: '复制成功',
		// 	type: 'success',
		// });
	} else {
		// 创建文本域
		const textArea = document.createElement('textarea')
		// 赋值传入的内容
		textArea.value = text
		// 添加节点
		document.body.appendChild(textArea)
		// 使textarea不在viewport,同时设置不可见
		textArea.focus()
		textArea.select()
		// 提示
		// ElMessage({
		// 	message: '复制成功',
		// 	type: 'success',
		// });
		return new Promise((res, rej) => {
			// 执行复制命令并移除文本框
			document.execCommand('copy') ? res() : rej()
			textArea.remove()

		})
	}
};
// const { } = toRefs(data)
</script>
<style scoped lang="scss"></style>

2、vue-clipboard3插件

  • 安装
npm install --save vue-clipboard3
  • 引入
  import useClipboard from 'vue-clipboard3';
  const { toClipboard } = useClipboard();
  • 使用
  const copy = async (val) => {
    try {
      await toClipboard(val);
      console.log('复制成功!')
    } catch (e) {
      console.log(e);
    }
  };