vuejs怎么实现复制功能

发布时间:2022-05-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了vuejs怎么实现复制功能脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

vuejs怎么实现复制功能

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

vuejs怎么实现复制功能?

vue.js实现一键copy功能

vuejs怎么实现复制功能

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

const vCopy = { // 名字爱取啥取啥
  /*
    bind 钩子函数,第一次绑定时调用,可以在这里做初始化设置
    el: 作用的 dom 对象
    value: 传给指令的值,也就是我们要 copy 的值
  */
  bind(el, { value }) {
    el.$value = value; // 用一个全局属性来存传进来的值,因为这个值在别的钩子函数里还会用到
    el.handler = () => {
      if (!el.$value) {
        // 值为空的时候,给出提示,我这里的提示是用的 ant-design-vue 的提示,你们随意
       console.LOG('无复制内容');
        return;
      }
      // 动态创建 textarea 标签
      const textarea = document.createElement('textarea');
      // 将该 textarea 设为 readonly 止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
      textarea.readOnly = 'readonly';
      textarea.style.posITion = 'absolute';
      textarea.style.left = '-9999px';
      // 将要 copy 的值赋给 textarea 标签的 value 属性
      textarea.value = el.$value;
      // 将 textarea 插入到 body 中
      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);
    };
    // 绑定点击事件,就是所谓的一键 copy 啦
    el.addEventListener('click', el.handler);
  },
  // 当传进来的值更新的时候触发
  componentUpdated(el, { value }) {
    el.$value = value;
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind(el) {
    el.removeEventListener('click', el.handler);
  },
};
export default vCopy;

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

import copy From './copyComm.js';
// 自定义指令
const directives = {
  copy,
};
// 这种写法可以批量注册指令
export default {
  install(Vue) {
    Object.keys(directives).foreach((key) => {
      Vue.directive(key, directives[key]);
    });
  },
};

3,在main.js注册

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

4,vue文件使用

<template>
  <div >
    <button v-copy="copyText">拷贝</button>
  </div>
</template>
<script>
  export default {
    data(){
      return {
        copyText:'要copy的内容'
      }
    },
    methods: {
      init () {
      },
    },
    watch: {},
    PRops: [],
    components: {},
    computed: {},
    mounted () {
      _this = this;
      _this.init();
    },
  }
</script>

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

以上就是vuejs怎么实现复制功能的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的vuejs怎么实现复制功能全部内容,希望文章能够帮你解决vuejs怎么实现复制功能所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:vuejs