
<span class="button" @click="copy(link)">复制</span>
copy(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text).then(
() => {
this.$toast('复制成功!')
},
err => {
console.error('err: ', err)
this.fallbackCopyTextToClipboard(text)
}
)
} else {
this.fallbackCopyTextToClipboard(text)
}
},
selectText(textbox, startIndex, stopIndex) {
if (textbox.createTextRange) {
const range = textbox.createTextRange()
range.collapse(true)
range.moveStart('character', startIndex)
range.moveEnd('character', stopIndex - startIndex)
range.select()
} else {
textbox.setSelectionRange(startIndex, stopIndex)
textbox.focus()
}
},
fallbackCopyTextToClipboard(copyTxt) {
const textArea = document.createElement('textarea')
textArea.style.position = 'fixed'
textArea.style.top = '0'
textArea.style.left = '0'
textArea.style.opacity = '0'
textArea.setAttribute('readonly', '')
textArea.value = copyTxt
document.body.appendChild(textArea)
textArea.focus()
textArea.select()
try {
if (document.execCommand('copy')) {
document.execCommand('copy')
this.$toast('复制成功')
} else {
this.selectText(textArea, 0, copyTxt.length)
if (document.execCommand('copy')) {
document.execCommand('copy')
this.$toast('复制成功!')
} else {
this.$toast('复制失败!')
}
}
} catch (err) {
this.$toast('无法复制')
}
document.body.removeChild(textArea)
},