时间:2022-06-23 11:39:30 | 栏目:vue | 点击:次
好久没接触vue的项目了,最近接到一个vue图片处理的小项目,有一项需求是要实现拖动图片就行排序。
接到这个需求之后立马想到了Vue.Draggable这款基于Sortable.js实现的vue拖拽插件
第一步:安装Vue.Draggable。两种方式npm和yarn (我用的npm)
npm i -S vuedraggable yarn add vuedraggable
第二步:全局安装完成之后在main.js中全局引用也行在需要的页面也用也没问题 (我因为就一个页面需要我就单页面引入的)
<script> import draggable from "vuedraggable" export default { components: { draggable } } </script>
第三步:安装和引用都完成了,现在开始使用了。
<template> <div class="col"> <draggable v-model="data" filter=".forbid" animation="300" :move="onMove"> <transition-group> <div v-for="(item, index) in data" :key="index"> <div class="img-hover"> <img :src="'http://xxxxx' + item.img"/> </div> </div> </transition-group> </draggable> </div> </template>
注意:
/** *代码中的data为你的数据列表,onMove为你在拖动图片是触发的函数方法。 *transition-group标签下一定是v-for循环,不然会报错。 **/
这样,一个简单的图片拖拽排序的简单demo就完成了。
npm i vuedraggable
import draggable from 'vuedraggable';
components: { draggable},
<template> <div class="app-container"> <div :class="canEdit? 'dargBtn-lock el-icon-unlock': 'dargBtn-lock el-icon-lock' " @click="removeEvent()">{{canEdit? '调整':'锁定'}}</div> <ul class="projset-content"> <draggable :move="onMove" :list="imgList" handle=".dargBtn" :animation="200" filter=".undraggable" > <li v-for="(item, index) in imgList" :key="index" :class="canEdit ? 'draggable' : 'undraggable'"> <div class="dargBtn"> <svg-icon icon-class="drag" /> </div> <img :src="item.path" alt=""> <span>{{item.name}}</span> </li> </draggable> </ul> </div> </template>
<script> import draggable from 'vuedraggable'; export default { components: { draggable}, data(){ return{ canEdit:true, imgList: [ { path: 'https://lupic.cdn.bcebos.com/20210629/3000005161_14.jpg', name: '1', }, { path: 'https://lupic.cdn.bcebos.com/20210629/26202931_14.jpg', name: '2', }, { path: 'https://lupic.cdn.bcebos.com/20210629/27788166_14.jpg', name: '3', } ] } }, created() { }, mounted(){}, methods:{ onMove(relatedContext, draggedContext){ console.log(relatedContext.relatedContext.list); }, removeEvent (item) { if(this.canEdit){ this.canEdit = false; }else{ this.canEdit = true; } console.log(this.canEdit); } } } </script>
<style scoped lang="scss"> .app-container{ background: #ffffff; height: 100%; .dargBtn-lock{ margin: 0px 50px; color: #2ea9df; } .projset-content{ list-style-type: none; position: relative; li{ display: inline-block; margin: 10px; } img{ width: 141px; height: 100px; } span{ justify-content: center; display: flex; } .dargBtn{ position: absolute; line-height: 100px; text-align: center; width: 141px; height: 100px; display: none; color: white; background: rgba(101, 101, 101, 0.6); } .draggable{ cursor: pointer; width: 141px; height: 100px; } .draggable:hover .dargBtn{ display: block; } } } </style>