当前位置:首页 > 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:

<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 实现单点登录(SSO)方案 单点登录(SSO)允许用户在多个相关但独立的系统中使用同一组凭证登录。以下是基于 Vue 的实现方案: 基于 OAuth2/OpenID Connect 的实现…

vue实现购票

vue实现购票

Vue 实现购票功能 数据结构设计 购票功能通常需要以下数据结构: 场次信息(时间、地点、价格) 座位信息(可选座位、已售座位) 用户订单信息 示例数据结构: data() { return…

vue 菜单实现

vue 菜单实现

Vue 菜单实现方法 在Vue中实现菜单功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for动态生成菜单 通过数据驱动的方式动态渲染菜单项,适合菜单内容可能变化的场景: <…

vue实现增加

vue实现增加

实现 Vue 中的新增功能 在 Vue 中实现新增功能通常涉及数据绑定、表单处理和状态管理。以下是几种常见的实现方式: 数据绑定与列表渲染 通过 v-model 绑定表单输入,使用数组的 pu…

vue实现复制

vue实现复制

Vue 实现复制功能 在 Vue 中实现复制功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 Clipboard API Clipboard API 是现代浏览器提供的一种原生 AP…

vue实现页面

vue实现页面

Vue 实现页面的基本方法 创建 Vue 项目 使用 Vue CLI 快速初始化项目,运行以下命令安装并创建项目: npm install -g @vue/cli vue create my-pro…