Vue - custom instructions, drag and drop to change the width of the element - skill improvement

When I was looking at the corporate WeChat recently, I found tapdthat the demand part is divided into two parts, the left and the right, and the left side can be dragged to change the width.
insert image description here
I feel that this kind of implementation effect is better, and I think of the same left and right layout when I wrote the performance structure before.
insert image description here
If the same effect can be achieved, it is a good experience.

The above effects can vuebe achieved in the form of instructions:

Go directly to the code:

1. utilsAdd in itdrag.js

/**
*拖拽改变宽度的指令
*/
export default {
    
    
	install(Vue){
    
    
		Vue.mixin({
    
    
			directives:{
    
    
				drag:{
    
    
					inserted:function(el){
    
    
						const dragDom = el;
						dragDom.style.cursor="e-resize";
						dragDom.onmousedown = e=>{
    
    
							//鼠标按下,计算当前元素距离可视区的距离
							const disX = e.clientX;
							const w = dragDom.clientWidth;
							const minW = 240;
							const maxW = 600;
							var nw;
							document.onmousemove = function(e){
    
    
								//通过事件委托,计算移动的距离
								const l = e.clientX - disX;
								//改变当前元素宽度,不可超过最小最大值
								nw = w + l;
								nw = nw < minW?minW:nw;
								nw = nw > maxW?maxW:nw;
								dragDom.style.width = `{nw}px`;
							}
							document.onmouseup = function(e){
    
    
								document.onmousemove = null;
								document.onmouseup = null;
							}
						}
					}
				}
			}
		})
	}
}

2. main.jsIntroduce and register in it

import drag from './utils/drag.js'
Vue.use(drag);

3. Use on the pagev-drag

<template>
	<div class="wrap">
		<div class="left" v-drag></div>
		<div class="right"></div>
	</div>
</template>

Finish! ! ! A lot of accumulation, a lot of harvest! ! !

Guess you like

Origin blog.csdn.net/yehaocheng520/article/details/131721881