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()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
前端小趴菜057 分钟前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~1 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
sasaraku.2 小时前
serviceWorker缓存资源
前端
iCxhust2 小时前
c# U盘映像生成工具
开发语言·单片机·c#
RadiumAg3 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
yanlele3 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
emplace_back4 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk4 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶4 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust