<template>
  <span class="copy" v-if="content">
    <slot/>{{text}}
    <i v-if="!!content" @click="copyText" title="复制" class="el-icon-document-copy"></i>
  </span>
</template>

<script>
import copy from 'copy-to-clipboard'

export default {
  name: 'copy-text',
  props: {
    text: {
      type: String,
      default: ''
    },
    hint: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      content: ''
    }
  },
  mounted() {
    this.getTextContent()
  },
  updated() {
    this.getTextContent()
  },
  methods: {
    getTextContent() {
      const slot = this.$slots.default || []
      const text = slot[0]?.text || this.text
      this.content = text
      return text
    },
    copyText() {
      const text = this.content
      if (text) {
        copy(text)
        if (this.hint) {
          this.$message.success('复制成功')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.copy{
  .el-icon-document-copy{
    cursor: pointer;
  }
}
</style>
