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()来清除浏览器的选区,这样可以防止某些浏览器在拖动过程中出现文本选择的情况。
相关推荐
LawrenceLan12 小时前
Flutter 零基础入门(十):final、const 与不可变数据
开发语言·flutter·dart
攀登的牵牛花12 小时前
前端向架构突围系列 - 框架设计(七):反应式编程框架Flower的设计
前端·架构
佛系打工仔12 小时前
K线绘制前言
前端
源代码•宸12 小时前
Leetcode—1266. 访问所有点的最小时间【简单】
开发语言·后端·算法·leetcode·职场和发展·golang
遇见~未来12 小时前
JavaScript数组全解析:从本质到高级技巧
开发语言·前端·javascript
南屿欣风12 小时前
Sentinel 熔断规则 - 异常比例(order & product 示例)笔记
java·开发语言
哈__12 小时前
基础入门 React Native 鸿蒙跨平台开发:TabBar 底部导航栏
javascript·react native·react.js
lili-felicity12 小时前
React Native 鸿蒙跨平台开发:Animated 实现鸿蒙端组件的左右滑动动画
javascript·react native·react.js
石像鬼₧魂石12 小时前
80 端口(Web 服务)渗透测试完整总结(含踩坑 + 绕过 + 实战流程)
linux·运维·服务器·前端·网络·阿里云
u01040583612 小时前
使用Java实现高性能的异步编程:CompletableFuture与Reactive Streams
java·开发语言