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()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
风骏时光牛马15 小时前
生成一个AI多模态标题,仅输出一条标题,无额外文字、问句、备选、配图、文案等任何附加内容,不需要其他的任务服务 只要标题。
前端
wangruofeng16 小时前
从 GIF 到 AVIF:网页图片格式演进与 2026 年选型指南
前端·架构
清晨Coding17 小时前
为什么用 React Developer Tools 查看组件树这么乱?
前端·react.js
johnjincaaaa17 小时前
猿人学第 18 题「jsvmp 洞察先机」逆向通关实录
javascript·后端
鶴哥只手遮天17 小时前
《Electron 45.2.3 内核解剖》第 4 章 补丁体系:380 个补丁改了什么
前端·electron
码农小河6618 小时前
基于PHP的电商后台蜜罐系统
开发语言·php
starzy199018 小时前
深入理解Scala柯里化函数:函数链式变换
开发语言·scala
ShineWinsu19 小时前
对于Qt:QTreeWidget常见属性以及QTreeWidgetItem类的解析
开发语言·c++·qt·gui·客户端·多叉树·qtreewidget
落羽的落羽19 小时前
【C++】C++17的主要特性
linux·服务器·开发语言·c++·算法·机器学习
FungLeo19 小时前
成为全栈·Vue 管理后台篇·分类树与标签管理:层级数据如何落到管理界面
前端·javascript·vue.js·分类树·naive ui·标签管理·前端数据结构