/ Gists / 03 copy to clipboard
On gists

03 copy to clipboard

cdruc vue

CopyToClipBoard.vue Raw #

<script>
export default {
  data() {
    return {
      status: 'idle',
    };
  },
  methods: {
    copy(text) {
      // create textarea
      const el = document.createElement('textarea');
      
      // assign value
      el.value = text;
      
      // style textarea
      el.style.position = 'absolute';
      el.style.left = '-90000px';
      document.body.appendChild(el);

      // select its contents
      el.select();
      
      // execute copy
      document.execCommand("copy");
      
      // remove textarea
      document.body.removeChild(el);

      this.status = "copied";
      setTimeout(() => this.status = "idle", 1000);
    },
  },
  render() {
    return this.$slots.default({
      status: this.status,
      copy: this.copy
    });
  }
};
</script>

Usage.vue Raw #

<CopyToClipboard v-slot="props">
  <button
      @click="props.copy(media.url)"
      :disabled="props.status === 'copied'"
      :class="[props.status === 'copied' ? 'text-green-600': 'text-blue-600 hover:text-blue-700']"
      class="text-xs rounded focus:outline-none focus:ring-2 focus:ring-blue-500">
    {{ props.status === 'copied' ? 'Copied!' : 'Copy' }}
  </button>
</CopyToClipboard>