index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { createApp } from 'vue'
  2. import Antd from 'ant-design-vue'
  3. // 导入组件
  4. import ShareFileDialog from './Dialog.vue'
  5. import snowy from '@/snowy'
  6. let shareFileInstance = null
  7. let shareFileApp = null
  8. /**
  9. * 初始化分享文件实例
  10. * @param {array} fileInfo 要分享的文件数组
  11. * @param {Function} callback 回调函数
  12. */
  13. const initInstanceShareFile = (fileInfo, callback) => {
  14. const mountNode = document.createElement('div')
  15. shareFileApp = createApp(ShareFileDialog, {
  16. fileInfo,
  17. callback
  18. })
  19. // 注册 Ant Design Vue 组件
  20. shareFileApp.use(Antd)
  21. shareFileApp.use(snowy)
  22. shareFileInstance = shareFileApp.mount(mountNode)
  23. return mountNode
  24. }
  25. /**
  26. * 分享文件 Promise 函数
  27. * @returns {Promise} 抛出确认和取消回调函数
  28. */
  29. const showShareFileDialog = (obj) => {
  30. // 非首次调用服务时,在 DOM 中移除上个实例
  31. if (shareFileInstance !== null && shareFileApp !== null) {
  32. shareFileApp.unmount()
  33. shareFileInstance = null
  34. shareFileApp = null
  35. }
  36. let { fileInfo } = obj
  37. return new Promise((resolve) => {
  38. const mountNode = initInstanceShareFile(fileInfo, (res) => {
  39. resolve(res)
  40. // 服务取消时卸载 DOM
  41. if (res === 'cancel' && shareFileInstance !== null) {
  42. shareFileApp.unmount()
  43. document.body.removeChild(mountNode)
  44. shareFileInstance = null
  45. shareFileApp = null
  46. }
  47. })
  48. document.body.appendChild(mountNode) // 挂载 DOM
  49. // 使用 setTimeout 替代 Vue.nextTick
  50. setTimeout(() => {
  51. if (shareFileInstance) {
  52. shareFileInstance.visible = true // 打开对话框
  53. }
  54. }, 0)
  55. })
  56. }
  57. export default showShareFileDialog