index.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <template>
  2. <div
  3. v-show="flag"
  4. :style="style"
  5. class="ibps-contextmenu"
  6. >
  7. <slot />
  8. </div>
  9. </template>
  10. <script>
  11. export default {
  12. name: 'ibps-contextmenu',
  13. props: {
  14. visible: {
  15. type: Boolean,
  16. default: false
  17. },
  18. menulist: {
  19. type: Array,
  20. default: () => []
  21. },
  22. x: {
  23. type: Number,
  24. default: 0
  25. },
  26. y: {
  27. type: Number,
  28. default: 0
  29. },
  30. zIndex: {
  31. type: Number
  32. }
  33. },
  34. data() {
  35. return {
  36. borderStyle: '',
  37. flag: false
  38. }
  39. },
  40. computed: {
  41. style() {
  42. return {
  43. left: this.x + 'px',
  44. top: this.y + 'px',
  45. display: this.visible ? 'block' : 'none ',
  46. zIndex: this.zIndex,
  47. border: this.menulist.length === 0 ? 'none' + '!important' : '1px solid #cfd7e5'
  48. }
  49. }
  50. },
  51. watch: {
  52. visible(val) {
  53. this.flag = val
  54. if (this.flag) {
  55. // 注册全局监听事件 [ 目前只考虑鼠标解除触发 ]
  56. window.addEventListener('mousedown', this.watchContextmenu)
  57. }
  58. },
  59. flag: {
  60. handler(val) {
  61. this.$emit('update:visible', val)
  62. },
  63. deep: true
  64. }
  65. },
  66. mounted() {
  67. // 将菜单放置到body下
  68. document.querySelector('body').appendChild(this.$el)
  69. },
  70. destroyed() {
  71. if (this.$el && this.$el.remove) { this.$el.remove() }
  72. },
  73. methods: {
  74. watchContextmenu(event) {
  75. if (!this.$el.contains(event.target) || event.button !== 0) this.flag = false
  76. window.removeEventListener('mousedown', this.watchContextmenu)
  77. }
  78. }
  79. }
  80. </script>
  81. <style lang="scss">
  82. .ibps-contextmenu {
  83. position: absolute;
  84. padding: 5px 0;
  85. z-index: 2018;
  86. background: #FFF;
  87. border: 1px solid #cfd7e5;
  88. border-radius: 4px;
  89. box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  90. }
  91. </style>