useCopyCode
Usage
useCopyCode is a simple and practical composable that makes it easy to implement "copy to clipboard" functionality. It is an async function that returns a Promise<boolean> indicating whether the copy was successful.
The function prefers the modern, secure navigator.clipboard API. If the environment does not support it (e.g., on non-HTTPS pages or in older browsers), it automatically falls back to the legacy document.execCommand('copy') method to ensure maximum compatibility.
<script setup lang="ts">
import { useCopyCode } from '@movk/core'
import { ref } from 'vue'
const sourceText = ref('This is the text to be copied.')
const copied = ref(false)
const showMessage = ref(false)
async function handleCopy() {
const success = await useCopyCode(sourceText.value)
if (success) {
copied.value = true
showMessage.value = true
console.log('Text successfully copied to clipboard!')
setTimeout(() => showMessage.value = false, 2000)
}
else {
copied.value = false
showMessage.value = true
console.error('Copy failed.')
setTimeout(() => showMessage.value = false, 2000)
}
}
</script>
<template>
<div>
<textarea v-model="sourceText" rows="4" cols="50" />
<button @click="handleCopy">
{{ copied ? 'Copied!' : 'Copy text' }}
</button>
<p v-if="showMessage" :class="copied ? 'success' : 'error'">
{{ copied ? 'Copied successfully!' : 'Copy failed. Please check browser permissions or copy manually.' }}
</p>
</div>
</template>
<style scoped>
.success {
color: green;
}
.error {
color: red;
}
</style>
useCopyCode can only be executed in a client-side (browser) environment. If called on the server side (SSR), it will print a warning to the console and return false.API
useCopyCode(text)
Asynchronously copies the specified text string to the user's clipboard.
Parameters
Returns
true: indicates the text was copied successfully.false: indicates the copy failed.
Changelog
useAppStorage
A Vue composable that manages reactive localStorage or sessionStorage state with type-safe defaults, serialization, and cross-tab sync.
useInfiniteScrollBinding
A Vue composable wrapping VueUse useInfiniteScroll, adding a reactive canLoadMore guard so you control exactly when more items are fetched.