码迷,mamicode.com
首页 > 其他好文 > 详细

vue复制textarea文本域内容

时间:2018-09-01 19:18:44      阅读:596      评论:0      收藏:0      [点我收藏+]

标签:create   data   value   false   style   用户   方案   document   lse   

方案:找到textarea对象,获取焦点,选中textarea的所有内容,并调用document.execCommand("copy")
 
实现代码:
 
<template>
  <div>
    <textarea ref="letters"></textarea>
    <button @click="copyToClipboard(‘letters‘)">复制</button>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        loading: false
      }
    },
    created() {
      this.$nextTick(function () {
        this.$refs.letters.value = 用户名:张三\n性别:男\n电话号码:15812322222;
      })
    },
    methods: {
      //复制内容到粘贴板
      copyToClipboard(elemRef) {
        let target;
        let succeed = false;
        if(this.$refs[elemRef]){
          target = this.$refs[elemRef];
          // 选择内容
          let currentFocus = document.activeElement;
          target.focus();
          target.setSelectionRange(0, target.value.length);
          // 复制内容
          try {
            succeed = document.execCommand("copy");
            alert("内容复制成功");
          } catch (e) {
            succeed = false;
          }
          // 恢复焦点
          if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
          }
        }
        return succeed;
      },
    }
  }
</script>
 
复制完成后,在记事本等编辑器中粘贴即可。
 
 
 

vue复制textarea文本域内容

标签:create   data   value   false   style   用户   方案   document   lse   

原文地址:https://www.cnblogs.com/yeqrblog/p/9571129.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!