Vue custom instruction v-copy copy

vue custom command copy

In the vue project, you can directly copy the desired content by clicking the button.

Create a new project and modify the corresponding files in the following way (cv instant)

Using the custom instruction v-copy is actually assigning the content we want to copy to the cotpyTexts variable, and when the copy button is clicked, the content to be copied will be copied.

The first step is to create two new files directives.js and v-copy.js under src/directives.
insert image description here
The v-copy.js file code:

import {
    
     Message } from 'element-ui'
const vCopy = {
    
    
  /**
   * bind 钩子函数,第一次绑定时调用,可以在这里做初始化设置
   * el: 作用的 dom 对象
   * value: 传给指令的值,要 copy 的值
   */
  bind(el) {
    
    
    el.handel = () => {
    
    
      if (!el.$value) {
    
    
        Message({
    
    
          message: '无复制内容',
          type: 'warning'
        })
        return
      }
      const textarea = document.createElement('textarea')
      textarea.readOnly = 'readonly'
      textarea.style.position = 'absolute'
      textarea.style.left = '-99999x'
      textarea.value = el.$value
      document.body.appendChild(textarea)
      textarea.select()
      textarea.setSelectionRange(0, textarea.value.length)
      const result = document.execCommand('Copy')
      if (result) {
    
    
        Message({
    
    
          message: '复制成功',
          type: 'success'
        })
      }
      document.body.removeChild(textarea)
    }
    el.addEventListener('click', el.handel)
  },
  componentUpdated(el, {
     
      value }) {
    
    
    el.$value = value
  },
  // 指令与元素解绑的时候,移除事件绑定
  unbind(el) {
    
    
    el.removeEventListener('click', el.handel)
  }
}

export default vCopy

directives.js file:

import copy from './v-copy'

// 自定义指令
const directives = {
    
    
  copy
}
// 批量注册指令
export default {
    
    
  install(Vue) {
    
    
    Object.keys(directives).forEach(key => {
    
    
      Vue.directive(key, directives[key])
    })
  }
}

You can use v-copy directly in the vue page: role.vue

<template>
  <div>
    <el-button v-copy="copyValue" round class="copy-btn">复制</el-button>
    <el-button round class="copy-btn clear-btn" @click="clear">清空 </el-button>
  </div>
</template>
<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      copyValue: ''
    }
  },
  created() {
    
    
    this.convertResFile()
  },

  methods: {
    
    
    async convertResFile() {
    
    
      try {
    
    
        const res = await getVexConvertRes()
        if (res.code === 200) {
    
    
          this.copyValue = res.data
        }
      } catch (error) {
    
    
        this.$message.error(error)

        this.copyValue = ''
      }
    },
    clear() {
    
    
      this.copyValue = ''
    }
  }
}
</script>



Guess you like

Origin blog.csdn.net/weixin_44834981/article/details/128812300