跳到主要内容

v-copy

2023年11月06日
柏拉文
越努力,越幸运

一、认识


二、实现


2.1 定义

import { App } from 'vue';

const vCopy = {
install(app: App<Element>, _options: any) {
app.directive('copy', {
mounted: (el: any, binding: any) => {
el.$value = binding.value || el.innerText;
el.handler = () => {
if (!el.$value) {
console.log('无复制内容');
return;
}
const textarea: any = document.createElement('textarea');
textarea.readOnly = 'readonly';
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.value = el.$value;
document.body.appendChild(textarea);
textarea.select();
const result = document.execCommand('Copy');
if (result) {
console.log('复制成功!');
}
document.body.removeChild(textarea);
};
el.addEventListener('click', el.handler);
},
updated: (el: any, binding: any) => {
el.$value = binding.value;
}
});
}
};

export default vCopy;

2.2 安装

import App from './App.vue';
import { createApp } from 'vue';
import vCopy from './directives/vCopy';

import img1 from './assets/images/001.jpg';

const app = createApp(App);

app.use(vCopy, {});

app.mount('#app');

三、应用


<template>
<div v-copy>这是一个很寂寞的天,下着有些伤心的雨</div>
</template>

<script lang="ts" setup></script>