vue项目中使用sortable实现对块元素拖拽进行排序

下载:
npm install sortablejs --save

引入:
import Sortable from ‘sortablejs’

使用:

<template>
  <div class="flex" id="items">
    <div class="item" v-for="(item,index) in value">
      <p>{{item.name}}</p>
    </div>
  </div>
</template>
<style scope>
  .item{
    width: 100px;
    height: 100px;
    border: solid 1px #ccc;
  }
  .flex{
    display: flex;
    justify-content: space-around;
  }
</style>

<script>
import Sortable from 'sortablejs'
export default {
  name: 'operationsAdd',
  data () {
    return {
      value: [
        { name: 11111 },
        { name: 22222 },
        { name: 33333 },
        { name: 44444 }
      ]
    }
  },
  methods: {
    test() {
      var that = this
      var el = document.getElementById('items')
      // 常用
      new Sortable(el, {
        onEnd: function (evt) {
         // 获取排序之后的data数据
          that.value.splice(evt.newIndex, 0, that.value.splice(evt.oldIndex, 1)[0])
          var newArray = that.value.slice(0)
          that.value = []
          that.$nextTick(function () {
            that.value = newArray
            console.log(that.value)
          })
        }
      })
    }
  },
  mounted () {
    this.test()
  }
}
</script>
Logo

前往低代码交流专区

更多推荐