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()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
码农小韩2 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
木风小助理3 分钟前
`mapfile`命令详解:Bash中高效的文本至数组转换工具
开发语言·chrome·bash
前端工作日常11 分钟前
我学习到的AG-UI的概念
前端
yyy(十一月限定版)12 分钟前
初始matlab
开发语言·matlab
LawrenceLan13 分钟前
Flutter 零基础入门(九):构造函数、命名构造函数与 this 关键字
开发语言·flutter·dart
listhi52013 分钟前
基于MATLAB的支持向量机(SVM)医学图像分割方法
开发语言·matlab
韩师傅16 分钟前
前端开发消亡史:AI也无法掩盖没有设计创造力的真相
前端·人工智能·后端
hui函数18 分钟前
如何解决 pip install 编译报错 g++: command not found(缺少 C++ 编译器)问题
开发语言·c++·pip
Tisfy27 分钟前
网站访问耗时优化 - 从数十秒到几百毫秒的“零成本”优化过程
服务器·开发语言·性能优化·php·网站·建站
XiaoYu200230 分钟前
第12章 支付宝SDK
前端