1.定义一个指令方法:
Vue.directive('horizontalDrag', {
bind: function (el, binding) {
const dragbar = el.querySelector('.dragbar');
dragbar.onmousedown = e => {
const disX = el.offsetLeft;
console.log('disX:', disX);
document.onmousemove = function (e) {
e.preventDefault();
const l = e.clientX - 100;
if (l > 200) {
el.style.width = `${l}px`;
}
};
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
};
};
},
update(el, binding) {
if (!binding.value.contentShow) {
el.style.marginLeft = -el.offsetWidth + 'px';
} else {
el.style.marginLeft = '0px';
}
},
})
2.在vue文件中使用:
<template>
<div class="common-template-content">
<div
class="common-template-content-left"
v-horizontalDrag
>
<div>
//容器内容
</div>
<label class="dragbar"></label>
</div>
<div class="common-template-content-right"></div>
</div>
</template>
<style scoped lang="less">
.common-template-content {
display: flex;
}
/deep/.common-template-content-right {
margin-left: calc(20rem / 100);
position: relative;
overflow: hidden;
}
.common-template-content-left {
background: #fff;
width: calc(240rem / 100);
padding: calc(12rem / 100) calc(10rem / 100);
box-shadow: 0 calc(5rem / 100) calc(12rem / 100) #e8e8e8;
border-right: calc(1rem / 100) transparent solid;
border-top: calc(1rem / 100) transparent solid;
display: flex;
flex-direction: column;
height: 100%;
transition: margin 0.7s;
position: relative;
.dragbar {
width: 20px;
height: 100%;
position: absolute;
right: -10px;
cursor: ew-resize;
}
}
</style>