1. 程式人生 > 實用技巧 >Vue的拖拽

Vue的拖拽

一、描述

之前用 vue 寫過一個線上的多二維碼生成服務,體驗地址:https://postbird.gitee.io/vue-online-qrcode/

後面發現二維碼多了之後有時候想要排序,需要將比較重要的放在上面或者第一個,因此拖拽排序的需求就出來了。

知道 vue 肯定是有元件存在的,因此就直接搜了搜,找了兩個不同的庫分別是:

兩個庫的裡面不同,一個是直接進行元件封裝,一個是進行指令封裝。

二、vuedraggable

vuedraggable是標準的元件式封裝,並且將可拖動元素放進了transition-group

上面,過渡動畫都比較好。

使用方式:

yarn add vuedraggable

import vuedraggable from 'vuedraggable';

在使用的時候,可以通過v-model來雙向繫結本地 data,如果需要更新或者是觸發父元件監聽的事件,可以在updated()中去emit

引入後直接宣告該元件然後使用即可,示例程式碼:

<template>
  <vuedraggable class="wrapper" v-model="list">
    <transition-group>
      <div v-for="
item in list" :key="item" class="item"> <p>{{item}}</p> </div> </transition-group> </vuedraggable> </template> <script> import vuedraggable from 'vuedraggable'; export default { name: 'HelloWorld', components: {vuedraggable}, props: { }, data() {
return { list: [1,2,34,4,54,5] } }, updated() { console.log(this.list) }, methods: { } } </script> <style scoped> .wrapper { display: flex; justify-content: center; width: 100%; } .item{ width: 300px; height: 50px; background-color: #42b983; color: #ffffff; } </style>

實現的效果:

官方的示例:

官方的示例 gif:

更多的事件及使用方法請參閱:

三、Awe-dnd

vue-dragging的 npm 包的名字是awe-dnd,並不是 vue-dragging,這個庫的特點是封裝了v-dragging全域性指令,然後通過全域性指令去資料繫結等。

相比及 vuedraggable 來說, awe-dnd 是沒有雙向繫結(這裡沒有雙向繫結並不是很嚴謹,準確的來說沒有暴露雙向繫結的方式),因此提供了事件,在拖拽結束的時候用來更新列表(不需要手動更新列表,其實內部是實現了雙向繫結的)或者是去觸發父元件監聽的事件。

安裝依賴:

npm install awe-dnd --save
yarn add awe-and

使用:

import VueDND from 'awe-dnd'

Vue.use(VueDND)
<!--your.vue-->
<script>
export default {
  data () {
    return {
        colors: [{
            text: "Aquamarine"
        }, {
            text: "Hotpink"
        }, {
            text: "Gold"
        }, {
            text: "Crimson"
        }, {
            text: "Blueviolet"
        }, {
            text: "Lightblue"
        }, {
            text: "Cornflowerblue"
        }, {
            text: "Skyblue"
        }, {
            text: "Burlywood"
        }]
    }
  },
  /* if your need multi drag
  mounted: function() {
      this.colors.forEach((item) => {
          Vue.set(item, 'isComb', false)
      })
  } */
}
</script>

<template>
  <div class="color-list">
      <div
          class="color-item"
          v-for="color in colors" v-dragging="{ item: color, list: colors, group: 'color' }"
          :key="color.text"
      >{{color.text}}</div>
  </div>
</template>

可以發現繫結的時候v-dragging="{ item: color, list: colors, group: 'color' }"這種形式進行指令繫結,其中 item 就是單個物件,而 list 則是資料列表,group 則是用來宣告一個組,來保證可以在一個頁面中進行多個數據源的操作。

而提供的兩個事件方法如下:

export default {
  mounted () {
    this.$dragging.$on('dragged', ({ value }) => {
      console.log(value.item)
      console.log(value.list)
      console.log(value.otherData)
    })
    this.$dragging.$on('dragend', (res) => {
        console.error(res);
    })
  }
}

一般使用的方法就是:

this.$dragging.$on('dragend', (res) => {
   console.error(res);
})

效果: