vue自定义指令 v-copy 复制

vue自定义指令 copy

在vue 的项目里 当我们想直接在标签上加入 v-copy 就可以复制想要复制的内容该怎么做?

新建一个项目 按照以下方式把对应的文件改造下就可以了 (cv即食)

使用自定义指令 v-copy 其实就是把我们想要复制的内容赋值给cotpyTexts 这个变量,点击复制按钮的时候就把需要复制的内容复制过来了。
src/components/HelloWorld.vue

<template>
  <div>
    <button v-copy="copyTexts">复制</button>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {},
  data() {
    return {
      copyTexts: "复制的内容",
    };
  },

  methods: {},
};
</script>

<style scoped lang="less"></style>

自定义复制指令内容 src/directive/modules/copy.js


const copy = {
  bind(el, {
    value
  }) {
    el.$value = value
    el.handler = () => {
      if (!el.$value) {
        // 值为空的时候,给出提示。可根据项目UI仔细设计
        console.log('无复制内容')
        return
      }
      // 动态创建 textarea 标签
      const textarea = document.createElement('textarea')
      // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
      textarea.readOnly = 'readonly'
      textarea.style.position = 'absolute'
      textarea.style.left = '-9999px'
      textarea.style.width = 0
      textarea.style.height = 0

      // 将要 copy 的值赋给 textarea 标签的 value 属性
      textarea.value = el.$value
      // 将 textarea 插入到 body 中
      document.body.appendChild(textarea)
      // 选中值并复制
      textarea.select()
      const result = document.execCommand('Copy')

      if (result) {
        console.log('复制成功:', textarea.value) // 可根据项目UI仔细设计
      }
      document.body.removeChild(textarea)
    }
    // 绑定点击事件,就是所谓的一键 copy 啦
    el.addEventListener('click', el.handler)
  },
  // 当传进来的值更新的时候触发
  componentUpdated(el, {
    value
  }) {
    el.$value = value
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind(el) {
    el.removeEventListener('click', el.handler)
  },
}

export default copy

src/directive/index.js里面引入 把 copy.js 引入

import Vue from 'vue'
import copy from './modules/copy.js'
// 方式1
const files = require.context('./modules', false, /.+\.js$/)
// 按模块引入
// files.keys(): 打印出来为['./focus.js','/loadmore.js']
files.keys().forEach(fileName => {
  const directiveConfig = files(fileName) // 获取指令函数
  const directiveName = fileName // 获取指令名
    .replace(/^\.\//, '') // 去除开头的'./'
    .replace(/\.\w+$/, '') // 去除文件扩展名
  Vue.directive(directiveName, directiveConfig.default || directiveConfig)
})


// 方式2
// Vue.directive('copy', copy)

把自定义指令引入到main.js里面 src/main.js

import '@/directive/index.js' 

import App from './App.vue'
import Vue from 'vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端酱紫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值