clipboard.vue 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <template>
  2. <div class="">
  3. <div v-if="hasClipboard" class="">
  4. <div class="">window.navigator.clipboard</div>
  5. <v-btn @click="writeText()">写入剪贴板</v-btn>
  6. <v-btn @click="readText()">读取剪贴板</v-btn>
  7. </div>
  8. <div v-else class="">
  9. <span>当前环境不支持 window.navigator.clipboard</span>
  10. </div>
  11. <div class="">
  12. <div class="">copy-to-clipboard</div>
  13. <v-btn @click="syncCopy()">同步写入剪贴板</v-btn>
  14. <v-btn @click="asyncCopy()">异步写入剪贴板</v-btn>
  15. </div>
  16. </div>
  17. </template>
  18. <script>
  19. import copy from 'copy-to-clipboard';
  20. export default {
  21. auth: false,
  22. data() {
  23. return {
  24. hasClipboard: false,
  25. };
  26. },
  27. mounted() {
  28. this.hasClipboard = !!window.navigator.clipboard;
  29. },
  30. methods: {
  31. async writeText() {
  32. try {
  33. const now = Date.now();
  34. await navigator.clipboard.writeText(now);
  35. this.$toast.success(`写入成功 ${now}`);
  36. } catch (error) {
  37. this.$toast.error(`写入失败 ${error.message}`);
  38. }
  39. },
  40. async readText() {
  41. try {
  42. const clipText = await navigator.clipboard.readText();
  43. this.$toast.success(`读取成功 ${clipText}`);
  44. } catch (error) {
  45. this.$toast.error(`读取失败 ${error.message}`);
  46. }
  47. },
  48. syncCopy() {
  49. try {
  50. const now = Date.now();
  51. const res = copy(now, {
  52. debug: true,
  53. message: 'Press #{key} to copy',
  54. });
  55. if (!res) throw new Error('写入失败');
  56. this.$toast.success(`写入成功 ${now}`);
  57. } catch (error) {
  58. this.$toast.error(`写入失败 ${error.message}`);
  59. }
  60. },
  61. async asyncCopy() {
  62. try {
  63. await new Promise((resolve) => setTimeout(resolve, 1000));
  64. const now = Date.now();
  65. const res = copy(now, {
  66. debug: true,
  67. message: 'Press #{key} to copy',
  68. });
  69. if (!res) throw new Error('写入失败');
  70. this.$toast.success(`写入成功 ${now}`);
  71. } catch (error) {
  72. this.$toast.error(`写入失败 ${error.message}`);
  73. }
  74. },
  75. },
  76. };
  77. </script>