vue中 拖动元素边框 改变元素宽度
先上效果图:
如图所示,通过拖动来改变表单的宽度。
但实际上,这边并不是表单的边框,而是一个单独的组件。通过监听鼠标的down,move以及up事件。
我们可以单独的写个组件handle.vue。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | <template> <div class = "x-handle" @mousedown= "mouseDown" ></div> </template> <script> export default { name: "XHandle" , data() { return { lastX: "" }; }, created() { document.addEventListener( "mouseup" , this .mouseUp); }, destroyed() { document.removeEventListener( "mouseup" , this .mouseUp); }, methods: { mouseDown(event) { document.addEventListener( "mousemove" , this .mouseMove); this .lastX = event.screenX; }, mouseMove(event) { this .$emit( "widthChange" , this .lastX - event.screenX); this .lastX = event.screenX; console.log( this .lastX, "..." , event.screenX); }, mouseUp() { this .lastX = "" ; document.removeEventListener( "mousemove" , this .mouseMove); } } }; </script> <style lang= "less" > .x-handle { width: 2px; cursor: w-resize; z-index: 10; background: #ccc; } </style> |
监听事件并this.$emit将值传给父组件,父组件通过传过来的值来动态的修改需要改变宽度的元素。
如效果图所示,写一个有需求组件,并引入handle组件
1 2 3 4 | <div class = 'sss' > <div :style= "{ width: width + 'px' }" ></div> // 这里是你自己需要改变宽度的组件 <XHandle class = "myxhandle" @widthChange= "widthChange" /> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <script> import XHandle from "@/components/Xhandle" ; export default { data() { return { width: 700, }; }, components: { XHandle }, methods: { widthChange(movement) { console.log(movement, "~~~" ); this .width -= movement; if ( this .width < 300) { this .width = 300; } if ( this .width > 700) { this .width = 700; } } } }; </script> <style lang= "less" scoped> .sss { display: flex; } </style> |
这里将需要改变宽度的元素给一个双向绑定的值,然后通过子组件传来的值修改。再将两个元素弹性布局,相当于hanle组件就会
贴着我们需要拖动的元素,看上去是再拖动我们要改变宽度的元素,其实是在拖动我们的handle。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 2025成都.NET开发者Connect圆满结束
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 用一种新的分类方法梳理设计模式的脉络