您的位置:首页 > 技术中心 > 前端框架 >

vuejs怎么实现复制功能

时间:2022-02-23 17:47

vuejs实现复制功能的方法:1、创建一个copyComm.js的文件;2、创建一个directives.js文件来注册所有的全局指令;3、通过“return{copyText:'...'}”实现复制即可。

本文操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

vuejs怎么实现复制功能?

vue.js实现一键copy功能

4dce98adb2201d91830ddfd873eb10d.png

1,首先建一个copyComm.js的文件

  1. const vCopy = { // 名字爱取啥取啥
  2. /*
  3. bind 钩子函数,第一次绑定时调用,可以在这里做初始化设置
  4. el: 作用的 dom 对象
  5. value: 传给指令的值,也就是我们要 copy 的值
  6. */
  7. bind(el, { value }) {
  8. el.$value = value; // 用一个全局属性来存传进来的值,因为这个值在别的钩子函数里还会用到
  9. el.handler = () => {
  10. if (!el.$value) {
  11. // 值为空的时候,给出提示,我这里的提示是用的 ant-design-vue 的提示,你们随意
  12. console.log('无复制内容');
  13. return;
  14. }
  15. // 动态创建 textarea 标签
  16. const textarea = document.createElement('textarea');
  17. // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
  18. textarea.readOnly = 'readonly';
  19. textarea.style.position = 'absolute';
  20. textarea.style.left = '-9999px';
  21. // 将要 copy 的值赋给 textarea 标签的 value 属性
  22. textarea.value = el.$value;
  23. // 将 textarea 插入到 body 中
  24. document.body.appendChild(textarea);
  25. // 选中值并复制
  26. textarea.select();
  27. textarea.setSelectionRange(0, textarea.value.length);
  28. const result = document.execCommand('Copy');
  29. if (result) {
  30. console.log('复制成功');
  31. }
  32. document.body.removeChild(textarea);
  33. };
  34. // 绑定点击事件,就是所谓的一键 copy 啦
  35. el.addEventListener('click', el.handler);
  36. },
  37. // 当传进来的值更新的时候触发
  38. componentUpdated(el, { value }) {
  39. el.$value = value;
  40. },
  41. // 指令与元素解绑的时候,移除事件绑定
  42. unbind(el) {
  43. el.removeEventListener('click', el.handler);
  44. },
  45. };
  46. export default vCopy;

2,在建一个directives.js文件来注册所有的全局指令

  1. import copy from './copyComm.js';
  2. // 自定义指令
  3. const directives = {
  4. copy,
  5. };
  6. // 这种写法可以批量注册指令
  7. export default {
  8. install(Vue) {
  9. Object.keys(directives).forEach((key) => {
  10. Vue.directive(key, directives[key]);
  11. });
  12. },
  13. };

3,在main.js注册

  1. import Vue from 'vue';
  2. import Directives from './directives';
  3. Vue.use(Directives);

4,vue文件使用

  1. <template>
  2. <div >
  3. <button v-copy="copyText">拷贝</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data(){
  9. return {
  10. copyText:'要copy的内容'
  11. }
  12. },
  13. methods: {
  14. init () {
  15. },
  16. },
  17. watch: {},
  18. props: [],
  19. components: {},
  20. computed: {},
  21. mounted () {
  22. _this = this;
  23. _this.init();
  24. },
  25. }
  26. </script>

推荐:《最新的5个vue.js视频教程精选》

以上就是vuejs怎么实现复制功能的详细内容,更多请关注gxlsystem.com其它相关文章!

本类排行

今日推荐

热门手游