CopyButton.vue 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <template>
  2. <button title="Copy to clipboard" @click="copy(text)">
  3. <Icon
  4. name="clipboard"
  5. :class="copied ? 'fill-green-300' : 'fill-gray-200 hover:fill-white'"
  6. />
  7. <div v-if="copied" class="ml-2 absolute top-0 left-full text-green-300">
  8. Copied!
  9. </div>
  10. </button>
  11. </template>
  12. <script>
  13. export default {
  14. props: {
  15. text: { required: true },
  16. },
  17. data: () => ({
  18. copied: false,
  19. timeout: false,
  20. }),
  21. methods: {
  22. copy(text) {
  23. if (this.timeout) {
  24. window.clearTimeout(this.timeout);
  25. }
  26. const el = document.createElement('textarea');
  27. el.value = text;
  28. document.body.appendChild(el);
  29. el.select();
  30. document.execCommand('copy');
  31. document.body.removeChild(el);
  32. this.copied = true;
  33. this.timeout = window.setTimeout(() => (this.copied = false), 3000);
  34. },
  35. },
  36. };
  37. </script>