Vue 拖拽組件 vuedraggable 和 vue-dragging
一、描述
知道 vue 肯定是有組件存在的宦言,因此就直接搜了搜换薄,找了兩個(gè)不同的庫(kù)分別是:
兩個(gè)庫(kù)的里面不同藐唠,一個(gè)是直接進(jìn)行組件封裝,一個(gè)是進(jìn)行指令封裝爆土。
二椭懊、vuedraggable
vuedraggable
是標(biāo)準(zhǔn)的組件式封裝,并且將可拖動(dòng)元素放進(jìn)了 transition-group
上面步势,過(guò)渡動(dòng)畫(huà)都比較好氧猬。
使用方式:
yarn add vuedraggable
import vuedraggable from 'vuedraggable';
在使用的時(shí)候背犯,可以通過(guò) v-model
來(lái)雙向綁定本地 data,如果需要更新或者是觸發(fā)父組件監(jiān)聽(tīng)的事件盅抚,可以在 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>
實(shí)現(xiàn)的效果:
官方的示例:
官方的示例 gif:
更多的事件及使用方法請(qǐng)參閱:
三妄均、Awe-dnd
vue-dragging 的 npm 包的名字是 awe-dnd
柱锹,并不是 vue-dragging,這個(gè)庫(kù)的特點(diǎn)是封裝了 v-dragging
全局指令丛晦,然后通過(guò)全局指令去數(shù)據(jù)綁定等奕纫。
相比及 vuedraggable 來(lái)說(shuō), awe-dnd 是沒(méi)有雙向綁定(這里沒(méi)有雙向綁定并不是很嚴(yán)謹(jǐn)烫沙,準(zhǔn)確的來(lái)說(shuō)沒(méi)有暴露雙向綁定的方式)匹层,因此提供了事件,在拖拽結(jié)束的時(shí)候用來(lái)更新列表(不需要手動(dòng)更新列表锌蓄,其實(shí)內(nèi)部是實(shí)現(xiàn)了雙向綁定的)或者是去觸發(fā)父組件監(jiān)聽(tīng)的事件升筏。
安裝依賴:
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>
可以發(fā)現(xiàn)綁定的時(shí)候 v-dragging="{ item: color, list: colors, group: 'color' }"
這種形式進(jìn)行指令綁定,其中 item 就是單個(gè)對(duì)象瘸爽,而 list 則是數(shù)據(jù)列表您访,group 則是用來(lái)聲明一個(gè)組,來(lái)保證可以在一個(gè)頁(yè)面中進(jìn)行多個(gè)數(shù)據(jù)源的操作剪决。
而提供的兩個(gè)事件方法如下:
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);
})
效果: