当前位置:首页 > VUE

vue实现复制插件

2026-02-18 08:18:25VUE

使用 vue-clipboard2 插件

安装插件:

npm install vue-clipboard2

在 main.js 中引入并注册:

import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)

在组件中使用:

vue实现复制插件

<button v-clipboard:copy="textToCopy">复制文本</button>

使用原生 document.execCommand

创建自定义指令:

Vue.directive('copy', {
  bind(el, { value }) {
    el.$value = value
    el.handler = () => {
      const textarea = document.createElement('textarea')
      textarea.value = el.$value
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('Copy')
      document.body.removeChild(textarea)
    }
    el.addEventListener('click', el.handler)
  },
  unbind(el) {
    el.removeEventListener('click', el.handler)
  }
})

模板中使用:

vue实现复制插件

<button v-copy="textToCopy">复制</button>

使用 Clipboard API

现代浏览器方法:

methods: {
  async copyText(text) {
    try {
      await navigator.clipboard.writeText(text)
      console.log('复制成功')
    } catch (err) {
      console.error('复制失败:', err)
    }
  }
}

封装为通用组件

创建 CopyButton.vue:

<template>
  <button @click="handleCopy">
    <slot>复制</slot>
  </button>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      required: true
    }
  },
  methods: {
    async handleCopy() {
      try {
        await navigator.clipboard.writeText(this.text)
        this.$emit('copied')
      } catch {
        const textarea = document.createElement('textarea')
        textarea.value = this.text
        document.body.appendChild(textarea)
        textarea.select()
        document.execCommand('copy')
        document.body.removeChild(textarea)
        this.$emit('copied')
      }
    }
  }
}
</script>

标签: 插件vue
分享给朋友:

相关文章

vue实现框架

vue实现框架

Vue 框架实现的核心方法 基础项目搭建 使用 Vue CLI 或 Vite 快速初始化项目。Vue CLI 适合传统项目,Vite 更适合现代轻量级应用。安装后通过命令行工具选择所需配置(如 Rou…

vue 实现pdf

vue 实现pdf

在Vue中实现PDF功能 在Vue项目中实现PDF功能通常涉及PDF生成、预览或下载。以下是几种常见实现方式: 使用vue-pdf库预览PDF 安装依赖: npm install vue-pdf…

vue轮询实现

vue轮询实现

Vue 轮询实现方法 在 Vue 中实现轮询可以通过以下几种方式: 使用 setInterval data() { return { pollInterval: null } },…

vue实现计算

vue实现计算

Vue 实现计算的方法 在 Vue 中实现计算功能可以通过多种方式完成,主要包括计算属性(computed)、方法(methods)和侦听器(watch)。以下是具体的实现方法: 计算属性(Comp…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue分页实现

vue分页实现

实现Vue分页的几种方法 使用Element UI的分页组件 安装Element UI库后,可以直接使用其分页组件。以下是一个基本示例: <template> <div>…