index.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import contextMenuVue from './src/index';
  2. import { isClient } from '/@/utils/is';
  3. import { Options, Props } from './src/types';
  4. import { createApp } from 'vue';
  5. const menuManager: {
  6. doms: Element[];
  7. resolve: Fn;
  8. } = {
  9. doms: [],
  10. resolve: () => {},
  11. };
  12. export const createContextMenu = function (options: Options) {
  13. const { event } = options || {};
  14. try {
  15. event.preventDefault();
  16. } catch (e) {
  17. console.log(e);
  18. }
  19. if (!isClient) return;
  20. return new Promise((resolve) => {
  21. const wrapDom = document.createElement('div');
  22. const propsData: Partial<Props> = {};
  23. if (options.styles !== undefined) propsData.styles = options.styles;
  24. if (options.items !== undefined) propsData.items = options.items;
  25. if (options.event !== undefined) {
  26. propsData.customEvent = event;
  27. propsData.axis = { x: event.clientX, y: event.clientY };
  28. }
  29. createApp(contextMenuVue, propsData).mount(wrapDom);
  30. const bodyClick = function () {
  31. menuManager.resolve('');
  32. };
  33. const contextMenuDom = wrapDom.children[0];
  34. menuManager.doms.push(contextMenuDom);
  35. const remove = function () {
  36. menuManager.doms.forEach((dom: Element) => {
  37. try {
  38. document.body.removeChild(dom);
  39. } catch (error) {}
  40. });
  41. document.body.removeEventListener('click', bodyClick);
  42. document.body.removeEventListener('scroll', bodyClick);
  43. try {
  44. (wrapDom as any) = null;
  45. } catch (error) {}
  46. };
  47. menuManager.resolve = function (...arg: any) {
  48. resolve(arg[0]);
  49. remove();
  50. };
  51. remove();
  52. document.body.appendChild(contextMenuDom);
  53. document.body.addEventListener('click', bodyClick);
  54. document.body.addEventListener('scroll', bodyClick);
  55. });
  56. };
  57. export const unMountedContextMenu = function () {
  58. if (menuManager) {
  59. menuManager.resolve('');
  60. menuManager.doms = [];
  61. }
  62. };
  63. export * from './src/types';