一个使用js复制文本到剪贴板的小组件

这组件是基于elementui写的,除了复制剪贴板之外,还有悬浮提示、加载动画、多行隐藏,如果不需要的话可以自行更改

<template>
  <div v-loading="loading" class="">
    <el-popover :content="value || '暂无内容'" :close-delay="0" trigger="hover" placement="top" popper-class="cut-pop">
      <div slot="reference">
        <div v-if="value!==0 && !value" class="text-grey-light"></div>
        <div v-else class="cursor-pointer text-cut-3 text-xs" @click="handleCopy(value)">{{ value }}</div>
      </div>
    </el-popover>
  </div>
</template>

<script>
export default{
  name: 'CopyInput',
  props: {
    /**
     * 输入框的内容
     */
    value: {
      type: [Number, String],
      default: ''
    }
  },
  data: function() {
    return {
      loading: false
    }
  },
  methods: {
    handleCopy(value) {
      if (value) {
        this.loading = true
        var input = document.createElement('textarea') // 直接构建input
        input.value = value // 设置内容
        document.body.appendChild(input) // 添加临时实例
        input.select() // 选择实例内容
        const isbool = document.execCommand('Copy') // 执行复制
        if (isbool) {
          this.$message.success('复制成功:' + this.value.substring(0, 20) + (this.value.length > 20 ? '...' : ''))
          setTimeout(() => {
            this.loading = false
          }, 300)
        } else {
          this.$message.error({ message: '复制失败' })
          setTimeout(() => {
            this.loading = false
          }, 300)
        }
        document.body.removeChild(input) // 删除临时实例
      }
    }
  }
}
</script>

<style>
.text-cut-3{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}
.cut-pop.el-popover--plain{
  padding: 4px 4px;
  font-size: 12px;
  max-width: 300px;
  background: #fff;
  color: #666;
  border-color: #333;
}
</style>

 

posted @ 2021-07-12 14:30  Mankii  阅读(156)  评论(0编辑  收藏  举报
返回顶部