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>
復制完成后,在記事本等編輯器中粘貼即可。