当前位置:首页 > VUE

vue实现div拉伸

2026-03-26 21:58:50VUE

Vue 实现 Div 拉伸的方法

使用鼠标事件监听

通过监听 mousedownmousemovemouseup 事件实现 div 拉伸功能。在 Vue 的 methods 中定义相关事件处理函数,动态计算 div 的新尺寸。

<template>
  <div 
    class="resizable" 
    :style="{ width: width + 'px', height: height + 'px' }"
    @mousedown="startResize"
  ></div>
</template>

<script>
export default {
  data() {
    return {
      width: 200,
      height: 200,
      isResizing: false
    };
  },
  methods: {
    startResize(e) {
      this.isResizing = true;
      document.addEventListener('mousemove', this.resize);
      document.addEventListener('mouseup', this.stopResize);
    },
    resize(e) {
      if (this.isResizing) {
        this.width = e.clientX;
        this.height = e.clientY;
      }
    },
    stopResize() {
      this.isResizing = false;
      document.removeEventListener('mousemove', this.resize);
      document.removeEventListener('mouseup', this.stopResize);
    }
  }
};
</script>

<style>
.resizable {
  border: 1px solid #000;
  position: relative;
  cursor: se-resize;
}
</style>

使用 CSS resize 属性

利用 CSS 的 resize 属性可以快速实现 div 拉伸功能,但需要注意结合 overflow 属性使用。

<template>
  <div class="resizable-css"></div>
</template>

<style>
.resizable-css {
  width: 200px;
  height: 200px;
  border: 1px solid #000;
  resize: both;
  overflow: auto;
}
</style>

结合第三方库

使用如 vue-resizable 等第三方库可以更便捷地实现 div 拉伸功能,减少手动编写事件处理的代码量。

vue实现div拉伸

<template>
  <vue-resizable :active="['r', 'b', 'rb']" :width="200" :height="200">
    <div class="resizable-content"></div>
  </vue-resizable>
</template>

<script>
import VueResizable from 'vue-resizable';

export default {
  components: {
    VueResizable
  }
};
</script>

<style>
.resizable-content {
  width: 100%;
  height: 100%;
  border: 1px solid #000;
}
</style>

注意事项

  • 使用鼠标事件监听时,确保在组件销毁时移除事件监听,避免内存泄漏。
  • CSS resize 属性在某些浏览器中可能不支持所有方向,需测试兼容性。
  • 第三方库通常提供更多功能,如限制最小/最大尺寸、拖拽手柄等,适合复杂需求。

标签: vuediv
分享给朋友:

相关文章

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…

vue 路由 实现

vue 路由 实现

Vue 路由实现方法 Vue Router 是 Vue.js 的官方路由管理器,用于构建单页面应用(SPA)。以下是实现 Vue 路由的详细步骤: 安装 Vue Router 通过 npm 或 ya…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue实现pwa

vue实现pwa

Vue 实现 PWA 的步骤 Vue 结合 PWA(Progressive Web App)可以创建离线可用的 Web 应用。以下是实现方法: 安装 Vue CLI 并创建项目 确保已安装 Vue…

vue 实现报价

vue 实现报价

Vue 实现报价功能 在 Vue 中实现报价功能通常涉及前端表单交互、数据计算和与后端 API 的通信。以下是实现报价功能的几种常见方法: 表单设计与数据绑定 使用 Vue 的 v-model 指…

vue实现登录权限

vue实现登录权限

Vue 实现登录权限方案 路由守卫控制访问权限 安装vue-router并配置路由守卫,在全局前置守卫中检查用户登录状态和权限。未登录用户访问受限路由时重定向到登录页。 // router.js r…