<template>
<input type="text" v-model="message">
<button type="button" @click="onCopy()">复制
</button>
</template>
<script setup lang="ts">
import { ref,watch } from "vue"
import { useClipboard } from "@vueuse/core"
const {isSupported,copy,copied}=useClipboard()
const message=ref('0000000')
const onCopy=()=>{
if (!isSupported.value) {
window.$message.error("您的浏览器不支持复制功能!");
return;
}
copy(message.value);
}
watch(copied,(val)=>{
if(val)return alert(message.value)
})
</script>
<style scoped>
</style>
如果提醒 浏览器不支持复制 错误排除:
1.查看是否浏览器版本过低;
2.由于新版浏览器的安全策略,clipboard只有在安全域名下才可以访问,http域名下会显示undefined,但使用https开头的域名,或localhost,就可以访问navigator.clipboard。需要在调用useClipboard时加上legacy:true (legacy:true 仅支持9.4.0 以上版本)
const {isSupported,copy,copied } = useClipboard({ legacy: true })