yanjinhui
10 天以前 c5de0d98241f8c8349fa38851b77efcfc61e4d26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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 }