ElDragSelect.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <!--
  2. * @Descripttion:
  3. * @Author: liu.shiyi
  4. * @Date: 2023-03-14 10:20:54
  5. * @LastEditTime: 2023-05-23 15:14:47
  6. -->
  7. <template>
  8. <el-select
  9. ref="dragSelect"
  10. v-model="selectVal"
  11. v-bind="$attrs"
  12. class="drag-select"
  13. v-on="$listeners"
  14. >
  15. <slot />
  16. </el-select>
  17. </template>
  18. <script>
  19. import { EventBus } from 'data-room-ui/js/utils/eventBus'
  20. import Sortable from 'sortablejs'
  21. export default {
  22. name: 'DragSelect',
  23. props: {
  24. value: {
  25. type: [Array, String],
  26. required: true
  27. }
  28. },
  29. computed: {
  30. selectVal: {
  31. get () {
  32. if (Array.isArray(this.value)) {
  33. return [...this.value]
  34. } else {
  35. return this.value
  36. }
  37. },
  38. set (val) {
  39. if (Array.isArray(val)) {
  40. this.$emit('input', [...val])
  41. } else {
  42. this.$emit('input', val)
  43. }
  44. }
  45. }
  46. },
  47. watch: {
  48. // 监听数组变化,根据上次的数据的值,判断这次拖拽后数据是否变化,如果数据位置发生变化则出发emit事件
  49. selectVal: {
  50. handler (newVal, oldVal) {
  51. if (Array.isArray(newVal) && Array.isArray(oldVal)) {
  52. if ((newVal.length === oldVal.length) && (JSON.stringify(oldVal) !== JSON.stringify(newVal))) {
  53. // 告诉右侧的数据配置面板,选择器内的选项顺序发生变化,修改config的数据顺序
  54. this.$emit('valuePositionChange', newVal)
  55. // 告诉表格组件,表格列顺序发生变化
  56. EventBus.$emit('dragSelectChange', newVal)
  57. }
  58. }
  59. }
  60. }
  61. },
  62. created () {
  63. EventBus.$emit('dragSelectChange', this.selectVal)
  64. },
  65. mounted () {
  66. this.setSort()
  67. },
  68. methods: {
  69. setSort () {
  70. const el = this.$refs.dragSelect.$el.querySelectorAll(
  71. '.el-select__tags > span'
  72. )[0]
  73. if (el) {
  74. this.sortable = Sortable.create(el, {
  75. animation: 350,
  76. ghostClass: 'sortable-ghost',
  77. setData: function (dataTransfer) {
  78. dataTransfer.setData('Text', '')
  79. },
  80. onEnd: (evt) => {
  81. const targetRow = this.value.splice(evt.oldIndex, 1)[0]
  82. this.value.splice(evt.newIndex, 0, targetRow)
  83. }
  84. })
  85. }
  86. }
  87. }
  88. }
  89. </script>
  90. <style lang="scss" scoped>
  91. .drag-select {
  92. ::v-deep {
  93. .sortable-ghost {
  94. opacity: 0.8;
  95. color: #fff !important;
  96. background:var(--bs-el-color-primary) !important;
  97. }
  98. .el-tag {
  99. cursor: move;
  100. }
  101. }
  102. }
  103. </style>