vue3 实现滑动调整宽度的效果

<template>

<a-layout>

<a-layout-sider

v-model:collapsed="collapsed"

:width="sidebarWidth"

:style="{ overflow: 'visible' }"

@mousedown.stop="startResize($event)"

>

<div class="sider-resize" @mousedown.stop="startResize($event)"></div>

<!-- 侧边栏内容 -->

</a-layout-sider>

<a-layout>

<!-- 主体内容 -->

</a-layout>

</a-layout>

</template>

<script lang="ts">

import { defineComponent } from 'vue';

export default defineComponent({

data() {

return {

collapsed: false,

sidebarWidth: 200,

resizing: false,

startX: 0,

startWidth: 200,

moveHandler: null as null | ((event: MouseEvent) => void),

};

},

methods: {

startResize(event: MouseEvent) {

this.resizing = true;

this.startX = event.clientX;

this.startWidth = this.sidebarWidth;

this.moveHandler = this.resize.bind(this);

document.addEventListener('mousemove', this.moveHandler);

document.addEventListener('mouseup', this.stopResize);

},

resize(event: MouseEvent) {

if (this.resizing) {

const deltaX = event.clientX - this.startX;

this.sidebarWidth = Math.max(this.startWidth + deltaX, 100);

}

},

stopResize() {

this.resizing = false;

document.removeEventListener('mousemove', this.moveHandler!);

document.removeEventListener('mouseup', this.stopResize);

this.moveHandler = null;

window.getSelection()?.removeAllRanges();

},

},

});

</script>

<style>

.sider-resize {

position: absolute;

top: 0;

right: -5px;

width: 10px;

height: 100%;

cursor: col-resize;

}

</style>

  1. data中添加了moveHandler属性,用于存储resize方法的绑定版本。
  2. startResize方法中,使用bind创建了resize方法的绑定版本,并将其赋值给moveHandler
  3. stopResize方法中,使用removeEventListener移除了moveHandler指向的事件监听器,而不是直接移除resize方法。
  4. 同时,在stopResize方法中,我们调用了window.getSelection()?.removeAllRanges()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
Ulyanov9 小时前
深入QML-Python通信 构建响应式交互界面的桥梁设计:QML+PySide6现代开发入门(五)
开发语言·python·算法·交互·qml·系统仿真
就叫_这个吧9 小时前
JavaScript中常用事件示例展示附源码
开发语言·javascript·html
不会C语言的男孩9 小时前
C++ Primer Plus 第9章:内存模型和名称空间
开发语言·c++
zz34572981139 小时前
函数:python与c语言
c语言·开发语言·python
峥嵘life10 小时前
Android getprop 属性限制详解:User 版本属性获取问题分析
android·开发语言·python·学习
边界条件╝10 小时前
微前端进阶(二)
前端
郝学胜-神的一滴10 小时前
Qt 高级开发 019:从零定制登录窗口按钮、Logo 样式与交互悬浮效果
开发语言·c++·qt·程序人生·交互·用户界面
星夜夏空9910 小时前
FreeRTOS学习(5)——内存映射
开发语言·学习
代码N年归来仍是新手村成员10 小时前
【AWS】Lambda 初识与服务部署
javascript·react.js·ai·node.js·云计算·ai编程·aws
罗超驿10 小时前
9.零基础学CSS:元素属性设置(字体、颜色、对齐等)全解析
前端·css