[英]vue - copy password input field to clipboard
我的 vue 應用程序中有一個表單輸入,用於創建密碼。 我已經成功添加了一個按鈕來顯示/隱藏密碼。 我想將副本添加到剪貼板 function 以讓用戶將密碼復制並粘貼到安全的地方,但它不起作用。 我在這里做錯了什么?
模板代碼
<small class="font-wieght-bold text-success mb-0" v-if="isCopied">Copied</small>
<div class="input-group">
<input :type="showPassword ? 'text' : 'password'" class="form-control" ref="password" required v-model="password">
<div class="input-group-append">
<button class="btn btn-secondary" @click.prevent="copyToClipboard()"><i class="fas fa-clipboard"></i></button>
</div>
</div>
Vue代碼
viewPassword() {
this.showPassword = !this.showPassword;
},
copyToClipboard() {
this.$refs.password.select();
document.execCommand('copy');
this.isCopied = true;
setTimeout( () => { this.isCopied = !this.isCopied },3000);
}
您需要復制 v-model 的內容,而不是輸入本身。
您可以像這樣使用 function 從變量中復制。
它創建一個新文本框,使用復制命令,然后立即將其刪除。 所有這些都在一個事件循環中,因此它甚至永遠不會呈現。
const copyTextToClipboard = (text) => {
const textArea = document.createElement('textarea')
//
// *** This styling is an extra step which is likely not required. ***
//
// Why is it here? To ensure:
// 1. the element is able to have focus and selection.
// 2. if element was to flash render it has minimal visual impact.
// 3. less flakyness with selection and copying which **might** occur if
// the textarea element is not visible.
//
// The likelihood is the element won't even render, not even a flash,
// so some of these are just precautions. However in IE the element
// is visible whilst the popup box asking the user for permission for
// the web page to copy to the clipboard.
//
// Place in top-left corner of screen regardless of scroll position.
textArea.style.position = 'fixed'
textArea.style.top = '0'
textArea.style.left = '0'
// Ensure it has a small width and height. Setting to 1px / 1em
// doesn't work as this gives a negative w/h on some browsers.
textArea.style.width = '2em'
textArea.style.height = '2em'
// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0
// Clean up any borders.
textArea.style.border = 'none'
textArea.style.outline = 'none'
textArea.style.boxShadow = 'none'
// Avoid flash of white box if rendered for any reason.
textArea.style.background = 'transparent'
textArea.value = text
document.body.appendChild(textArea)
textArea.select()
try {
const successful = document.execCommand('copy')
const msg = successful ? 'successful' : 'unsuccessful'
console.log('Copying text command was ' + msg)
} catch (err) {
console.log('Oops, unable to copy')
}
document.body.removeChild(textArea)
}
作為已接受答案之一的替代解決方案,我嘗試使用剪貼板 API 。 特別是我使用了clipboard.writeText()方法將 v-modeled 數據直接復制到剪貼板中,它也可以與<input type="password">
一起使用。這是copyToClipboard()
方法的重構代碼:
copyToClipboard() {
navigator.clipboard.writeText(this.password);
this.isCopied = true;
setTimeout( () => { this.isCopied = !this.isCopied },3000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.