14.如何在Vue 3中通过Vue-drag-resize组件实现拖拽功能,

书诚小驿2024/12/20前端知识库Vue3

前言

在 Vue 3 中,我们可以通过 Vue-drag-resize 组件实现拖拽功能,该组件提供了拖拽、缩放、旋转、拖拽到指定位置、拖拽到指定元素等功能。

官方文档: 官方文档地址open in new window

预览地址: 预览地址open in new window

image.png

文档是参考的 vue2 框架,vue3 框架的文档还没有更新,所以这里只介绍 vue3 框架的用法。

1、安装

1、安装组件

npm install vue-drag-resize
npm i vant
npm add vant@^4 @vant/compat@^1
  1. 修改 package.json 的 dependencies 字段
{
  "dependencies": {
-    "vant": "^3.0.0",
+    "vant": "^4.0.0",
+    "@vant/compat": "^1.0.0",
  }
}

2、全局引入

  1. 全局引入main.js
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { Toast } from "vant";
import "vant/lib/index.css";
const app = createApp(App);
app.use(Toast).mount("#app");

3、Test.vue演示

<template>
  <div class="wrapper">
    <div class="head"></div>
    <div class="box">
      <VueDragResize
        :isActive="isActive"
        :parentLimitation="true"
        :w="58"
        :h="58"
        :x="40"
        :y="40"
        :minw="58"
        :minh="58"
        :isResizable="false"
        @resizestop="handleResizeStop($event, item)"
        @dragging="dragging"
        @dragstop="isActive = false"
        @activated="clickMessageBoard"
      >
        <div class="edit">弹窗</div>
      </VueDragResize>
    </div>
  </div>
</template>

<script setup>
  import VueDragResize from "vue-drag-resize/src";
  import { ref } from "vue";
  import { showToast } from "vant";
  const isActive = ref(false);
  const clickMessageBoard = () => {
    setTimeout(() => {
      if (isActive.value) {
        return;
      }
      showToast({
        message: "弹窗被点击了~",
        icon: "like-o",
      });
    }, 100);
  };
  /**
   * 处理窗口大小调整停止的事件。
   * @param {Event} e - 窗口大小调整停止的事件对象。
   * @description 当窗口大小调整停止时,此函数会被调用,并打印事件对象到控制台。
   */
  const handleResizeStop = (e) => {
    console.log(e);
  };
  /**
   * 拖动事件处理函数。
   * 当触发拖动事件时,该函数会被调用,并打印当前的激活状态,
   * 然后将激活状态设置为 true。
   */
  const dragging = () => {
    console.log("isActive", isActive.value);
    isActive.value = true;
  };
  /**
   * 拖动停止时的处理函数。
   * 当拖动操作结束时,此函数会被调用,将`isActive`状态设置为`false`。
   */
  const dragstop = () => {
    isActive.value = false;
  };
</script>

<style scoped>
  .wrapper {
    width: 100vw;
    height: 100vh;
    background: pink;
  }
  .head {
    width: 100vw;
    height: 100px;
  }
  .box {
    width: 100vw;
    height: calc(100vh - 100px);
    background: orange;
    position: relative;
  }
  .edit {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    line-height: 50px;
    text-align: center;
    background: blue;
  }

  ::v-deep(.vdr.active:before) {
    outline: none !important;
  }

  ::v-deep(.content-container) {
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>

image.png

image.png

最后更新时间' 2025/1/3 14:16:58