Vue 拖拽組件 vuedraggable 和 vue-dragging


一、描述

之前用 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> 

實現的效果:

22.gif

官方的示例:

官方的示例 gif:

https://raw.githubusercontent.com/SortableJS/Vue.Draggable/master/example.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); })

效果:

223.gif


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM