vue復制textarea文本域內容到粘貼板


vue實現復制內容到粘貼板
 
方案:找到textarea對象(input同樣適用),獲取焦點,選中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>
 
復制完成后,在記事本等編輯器中粘貼即可。
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM