vue实现拖拽效果,插件draggable

使用vue实现拖拽效果,插件draggable

在这里插入图片描述

安装依赖:

 npm install vuedraggable -S 

引入插件:

 import draggable from 'vuedraggable' 

注册组件:

components: {
    
    
  draggable
 }, 

下面是完整代码:

<template>
  <draggable
    v-model="colors"
    @update="datadragEnd"
    :options="{ animation: 500 }"
  >
    <transition-group>
      <div v-for="element in colors" :key="element.text" class="drag-item">
        {
    
    {
    
     element.text }}
      </div>
      <!-- 或者使用下面自定义,注意需要加key -->
	  <!-- 
	  <div class="drag-item" :key="1">11111</div>
      <div class="drag-item" :key="2">11111</div>
      <div class="drag-item" :key="3">11111</div>
       -->
    </transition-group>
  </draggable>
</template>

<script>
import draggable from "vuedraggable";
export default {
    
    
  data() {
    
    
    return {
    
    
      msg: "这是测试组件",
      colors: [
        {
    
    
          text: "列表1",
        },
        {
    
    
          text: "列表2",
        },
        {
    
    
          text: "列表3",
        },
        {
    
    
          text: "列表4",
        },
        {
    
    
          text: "列表5",
        },
        {
    
    
          text: "列表6",
        },
        {
    
    
          text: "列表7",
        },
        {
    
    
          text: "列表8",
        },
        {
    
    
          text: "列表9",
        },
      ],
      startArr: [],
      endArr: [],
      count: 0,
    };
  },
  components: {
    
    
    draggable,
  },
  methods: {
    
    
    getdata(evt) {
    
    
      console.log(evt.draggedContext.element.text);
    },
    datadragEnd(evt) {
    
    
      evt.preventDefault();
      console.log("拖动前的索引 :" + evt.oldIndex);
      console.log("拖动后的索引 :" + evt.newIndex);
      console.log(this.colors);
    },
  },
  mounted() {
    
    
    //为了防止火狐浏览器拖拽的时候以新标签打开,此代码真实有效
    document.body.ondrop = function (event) {
    
    
      event.preventDefault();
      event.stopPropagation();
    };
  },
};
</script>

<style lang="scss" scoped>
.test {
    
    
  border: 1px solid #ccc;
}
.drag-item {
    
    
  width: 200px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  margin: auto;
  position: relative;
  background: rgb(68, 226, 5);
  margin-top: 20px;
  color: #fff;
}
.ghostClass {
    
    
  opacity: 1;
}
.bottom {
    
    
  width: 200px;
  height: 50px;
  position: relative;
  background: blue;
  top: 2px;
  left: 2px;
  transition: all 0.5s linear;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_46476460/article/details/108978473