perf: useClipboard
parent
99ffe6a86a
commit
1db22482b4
@ -0,0 +1,47 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const useClipboard = () => {
|
||||||
|
const copied = ref(false)
|
||||||
|
const text = ref('')
|
||||||
|
const isSupported = ref(false)
|
||||||
|
|
||||||
|
if (!navigator.clipboard && !document.execCommand) {
|
||||||
|
isSupported.value = false
|
||||||
|
} else {
|
||||||
|
isSupported.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const copy = (str: string) => {
|
||||||
|
if (navigator.clipboard) {
|
||||||
|
navigator.clipboard.writeText(str).then(() => {
|
||||||
|
text.value = str
|
||||||
|
copied.value = true
|
||||||
|
resetCopied()
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const input = document.createElement('input')
|
||||||
|
input.setAttribute('readonly', 'readonly')
|
||||||
|
input.setAttribute('value', str)
|
||||||
|
document.body.appendChild(input)
|
||||||
|
input.select()
|
||||||
|
input.setSelectionRange(0, 9999)
|
||||||
|
if (document.execCommand('copy')) {
|
||||||
|
text.value = str
|
||||||
|
document.execCommand('copy')
|
||||||
|
copied.value = true
|
||||||
|
resetCopied()
|
||||||
|
}
|
||||||
|
document.body.removeChild(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetCopied = () => {
|
||||||
|
setTimeout(() => {
|
||||||
|
copied.value = false
|
||||||
|
}, 1500)
|
||||||
|
}
|
||||||
|
|
||||||
|
return { copy, text, copied, isSupported }
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useClipboard }
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ContentWrap } from '@/components/ContentWrap'
|
||||||
|
import { useClipboard } from '@/hooks/web/useClipboard'
|
||||||
|
import { ElButton, ElInput } from 'element-plus'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const { copy, copied, text, isSupported } = useClipboard()
|
||||||
|
|
||||||
|
const source = ref('')
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ContentWrap title="useClipboard">
|
||||||
|
<ElInput v-model="source" placeholder="请输入要复制的内容" />
|
||||||
|
<div v-if="isSupported">
|
||||||
|
<ElButton @click="copy(source)" type="primary" class="mt-20px">
|
||||||
|
<span v-if="!copied">复制</span>
|
||||||
|
<span v-else>已复制</span>
|
||||||
|
</ElButton>
|
||||||
|
<p>
|
||||||
|
当前已复制: <code>{{ text || 'none' }}</code>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p v-else> 你的浏览器不支持 Clipboard API </p>
|
||||||
|
</ContentWrap>
|
||||||
|
</template>
|
||||||
Loading…
Reference in New Issue