Files
mengyastore/mengyastore-frontend/src/modules/store/composables/useClipboardFeedback.js
2026-05-13 12:11:46 +08:00

45 lines
1.0 KiB
JavaScript

import { ref } from 'vue'
const DEFAULT_MS = 2000
/**
* Clipboard copy with short-lived button hint ("已复制" / "复制失败").
*/
export function useClipboardFeedback(resetMs = DEFAULT_MS) {
const hint = ref('')
let timer = null
const copy = async (text) => {
if (!text) return
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
const ta = document.createElement('textarea')
ta.value = text
ta.setAttribute('readonly', '')
ta.style.position = 'fixed'
ta.style.left = '-9999px'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
}
hint.value = '已复制'
} catch {
hint.value = '复制失败'
}
clearTimeout(timer)
timer = setTimeout(() => {
hint.value = ''
}, resetMs)
}
const dispose = () => {
clearTimeout(timer)
timer = null
}
return { hint, copy, dispose }
}