Skip to content

useCopyToClipboard

适用于 Vue3Nuxt3HTML

文本拷贝

示例

文本拷贝

查看代码
vue
<script setup lang="ts">
import { ref } from "vue";
import { useCopyToClipboard } from "@pureadmin/utils";
import { useMessage } from "../../components/message";

const { message } = useMessage();

let textValue = ref("");
const { copied, update } = useCopyToClipboard("当值为空时我会被拷贝");

function copy() {
  update(textValue); // 更新要拷贝的文本值
  if (copied.value) {
    message.success("拷贝成功");
  } else {
    message.warning("拷贝失败");
  }
}
</script>

<template>
  <naive-theme>
    <n-space className="mt-2 flex items-center">
      <n-input
        clearable
        type="text"
        v-model:value="textValue"
        placeholder="请输入要拷贝的值"
      />
      <n-button @click="copy"> 拷贝 </n-button>
    </n-space>
  </naive-theme>
</template>

代码片段拷贝

自动保留代码的空格、换行符和缩进

查看代码
vue
<script setup lang="ts">
import { ref } from "vue";
import { useCopyToClipboard } from "@pureadmin/utils";
import { useMessage } from "../../components/message";

const { message } = useMessage();

let codeValue = ref(`function sayHello() {
  console.log('Hello, World!');
}`);

const { copied, update } = useCopyToClipboard();

function copy() {
  update(codeValue); // 更新要拷贝的文本值
  if (copied.value) {
    message.success("拷贝成功");
  } else {
    message.warning("拷贝失败");
  }
}
</script>

<template>
  <naive-theme>
    <n-space className="mt-2 flex items-center">
      <n-code :code="codeValue" language="javascript" inline />
      <n-button @click="copy"> 拷贝 </n-button>
    </n-space>
  </naive-theme>
</template>

最简代码

拷贝文本

vue
<script setup lang="ts">
import { ref } from "vue";
import { useCopyToClipboard } from "@pureadmin/utils";

let textValue = ref(""); // 要拷贝的文本值
const { copied, update } = useCopyToClipboard();

function copy() {
  update(textValue); // 更新要拷贝的文本值
  if (copied.value) {
    //  拷贝成功
  }
}
</script>

<template>
  <button @click="copy">拷贝</button>
</template>

API

参数

ts
//  在此处配置参数
const {} = useCopyToClipboard(defaultValue);
参数属性必传说明类型
defaultValue当要拷贝的文本值为空时,拷贝的值,默认不设置string

返回值、方法

返回值、方法说明类型
clipboardValue拷贝后的文本值ShallowRef<string>
copied是否拷贝成功。true代表拷贝成功,false代表拷贝失败ShallowRef<boolean>
update更新要拷贝的文本值(value: string/Ref<string>) => void

Released under the MIT License