ElDragSelect.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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('.el-select__tags > span')[0]
  71. if (el) {
  72. this.sortable = Sortable.create(el, {
  73. animation: 350,
  74. ghostClass: 'sortable-ghost',
  75. setData: function (dataTransfer) {
  76. dataTransfer.setData('Text', '')
  77. },
  78. onEnd: (evt) => {
  79. const targetRow = this.value.splice(evt.oldIndex, 1)[0]
  80. this.value.splice(evt.newIndex, 0, targetRow)
  81. }
  82. })
  83. }
  84. }
  85. }
  86. }
  87. </script>
  88. <style lang="scss" scoped>
  89. .drag-select {
  90. ::v-deep {
  91. .sortable-ghost {
  92. opacity: 0.8;
  93. color: #fff !important;
  94. background:var(--bs-el-color-primary) !important;
  95. }
  96. .el-tag {
  97. cursor: move;
  98. }
  99. }
  100. }
  101. </style>