当前位置:首页 > VUE

vue实现复制插件

2026-02-18 08:18:25VUE

使用 vue-clipboard2 插件

安装插件:

npm install vue-clipboard2

在 main.js 中引入并注册:

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

在组件中使用:

<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)
  }
})

模板中使用:

<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:

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 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式,…

vue实现handsontable

vue实现handsontable

Vue 中实现 Handsontable 要在 Vue 项目中集成 Handsontable,可以使用官方提供的 @handsontable/vue 封装库。以下是一个完整的实现步骤。 安装依赖 确…

vue实现影院

vue实现影院

Vue实现影院功能的基本思路 使用Vue框架开发影院功能需要结合前端组件化开发、状态管理以及后端API交互。以下是关键实现步骤: 影院页面布局设计 影院页面通常分为顶部导航栏、影院列表区域和底部导航…

vue 实现图钉

vue 实现图钉

实现图钉效果的步骤 在Vue中实现图钉(固定位置)效果,可以通过CSS的position: sticky属性或监听滚动事件动态修改元素样式。以下是两种常见方法: 方法一:使用CSS的posi…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…

vue实现伸缩

vue实现伸缩

Vue实现伸缩功能的方法 使用CSS过渡和Vue的v-if或v-show 通过CSS的transition属性结合Vue的条件渲染指令(v-if或v-show)可以实现元素的伸缩效果。定义一个CSS类…