vuejs如何实现复制粘贴功能,下面编程教程网小编给大家详细介绍一下实现代码!
新建copy.js的文件
const vCopy = {
bind(el, { value }) {
el.$value = value;
el.handler = () => {
if (!el.$value) {
console.log('无复制内容');
return;
}
const textarea = document.createElement('textarea');
textarea.readOnly = 'readonly';
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.value = el.$value;
document.body.appendChild(textarea);
// 选中值并复制
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const result = document.execCommand('Copy');
if (result) {
console.log('复制成功');
}
document.body.removeChild(textarea);
};
el.addEventListener('click', el.handler);
},
componentUpdated(el, { value }) {
el.$value = value;
},
unbind(el) {
el.removeEventListener('click', el.handler);
},
};
export default vCopy;
新建directives.js文件
import copy from './copy.js';
// 自定义指令
const directives = {
copy,
};
export default {
install(Vue) {
Object.keys(directives).forEach((key) => {
Vue.directive(key, directives[key]);
});
},
};
main.js全局引入
import Vue from 'vue';
import Directives from './directives';
Vue.use(Directives);
页面调用
<template>
<div >
<button v-copy="copyText">拷贝</button>
</div>
</template>
<script>
export default {
data(){
return {
copyText:'要copy的内容'
}
},
methods: {
init () {
},
},
mounted () {
_this = this;
_this.init();
},
}
</script>
以上是编程学习网小编为您介绍的“vuejs如何实现复制粘贴功能”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
沃梦达教程
本文标题为:vuejs如何实现复制粘贴功能


猜你喜欢
- javascript实现的网站访问量统计代码 2023-12-23
- vue利用chinese-to-english插件实现中文转英文 2025-01-13
- DIV+CSS实现电台列表设计的示例代码 2024-02-05
- React Native中NavigatorIOS组件的简单使用详解 2023-12-24
- threejs后期处理的基本使用方法之加特效 2023-12-25
- JavaScript开发小技巧之数组技巧 2024-12-08
- AJAX+JSP实现读取XML内容并按排列显示输出的方法示例 2023-02-15
- CSS实现body背景层高于块元素的方法 2024-03-11
- jQuery 实现图片的依次加载图片功能 2024-01-04
- vue3.x keep-alive不生效 2023-10-08