index.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Clipboard from 'clipboard'
  2. import { Directive, DirectiveBinding } from 'vue'
  3. import { Message } from '_c/Message'
  4. if (!Clipboard) {
  5. throw new Error('you should npm install `clipboard` --save at first ')
  6. }
  7. export const clipboard: Directive = {
  8. beforeMount(el: HTMLElement, binding: DirectiveBinding) {
  9. createdClipboard(el, binding.arg, binding.value)
  10. },
  11. updated(el: HTMLElement | any, binding: DirectiveBinding) {
  12. if (binding.arg === 'success') {
  13. el._v_clipboard_success = binding.value
  14. } else if (binding.arg === 'error') {
  15. el._v_clipboard_error = binding.value
  16. } else {
  17. el._v_clipboard.text = function() { return binding.value }
  18. el._v_clipboard.action = function() { return 'copy' }
  19. }
  20. },
  21. unmounted(el: HTMLElement | any, binding: DirectiveBinding) {
  22. if (binding.arg === 'success') {
  23. delete el._v_clipboard_success
  24. } else if (binding.arg === 'error') {
  25. delete el._v_clipboard_error
  26. } else {
  27. el._v_clipboard.destroy()
  28. delete el._v_clipboard
  29. }
  30. }
  31. }
  32. function createdClipboard(el: HTMLElement | any, arg: string | undefined, value: any) {
  33. if (arg === 'success') {
  34. el._v_clipboard_success = value
  35. } else if (arg === 'error') {
  36. el._v_clipboard_error = value
  37. } else {
  38. const clipboard = new Clipboard(el, {
  39. text() { return value },
  40. action() { return 'copy' }
  41. })
  42. clipboard.on('success', e => {
  43. const callback = el._v_clipboard_success
  44. if (callback) {
  45. callback(e)
  46. } else {
  47. Message.success('复制成功')
  48. }
  49. })
  50. clipboard.on('error', e => {
  51. const callback = el._v_clipboard_error
  52. if (callback) {
  53. callback(e)
  54. } else {
  55. Message.success('复制失败')
  56. }
  57. })
  58. el._v_clipboard = clipboard
  59. }
  60. }