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()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
workflower19 分钟前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
CoderYanger1 小时前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
C++业余爱好者1 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
林杜雨都1 小时前
Action和Func
开发语言·c#
皮卡龙1 小时前
Java常用的JSON
java·开发语言·spring boot·json
火山灿火山2 小时前
Qt常用控件(三)
开发语言·qt
PineappleCoder2 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪2 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯2 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
利刃大大2 小时前
【JavaSE】十三、枚举类Enum && Lambda表达式 && 列表排序常见写法
java·开发语言·枚举·lambda·排序