ElDragSelect.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. }
  57. }
  58. }
  59. },
  60. created () {
  61. },
  62. mounted () {
  63. this.setSort()
  64. },
  65. methods: {
  66. setSort () {
  67. const el = this.$refs.dragSelect.$el.querySelectorAll('.el-select__tags > span')[0]
  68. if (el) {
  69. this.sortable = Sortable.create(el, {
  70. animation: 350,
  71. ghostClass: 'sortable-ghost',
  72. setData: function (dataTransfer) {
  73. dataTransfer.setData('Text', '')
  74. },
  75. onEnd: (evt) => {
  76. const targetRow = this.value.splice(evt.oldIndex, 1)[0]
  77. this.value.splice(evt.newIndex, 0, targetRow)
  78. }
  79. })
  80. }
  81. }
  82. }
  83. }
  84. </script>
  85. <style lang="scss" scoped>
  86. .drag-select {
  87. ::v-deep {
  88. .sortable-ghost {
  89. opacity: 0.8;
  90. color: #fff !important;
  91. background:var(--bs-el-color-primary) !important;
  92. }
  93. .el-tag {
  94. cursor: move;
  95. }
  96. }
  97. }
  98. </style>