vue常用自定义指令(resize,拖拽)

代码以main.js写法为例

一. 元素尺寸变化 v-risize

适用于监听元素大小变化;当窗口宽度不变,元素宽度变化时获取监听使用回调;
例如左侧导航栏可伸缩时,右侧元素的自适应

//main.js  //注册自定义指令 v-resize
app.directive('resize', {
    mounted(el, binding) { // el为绑定的元素,binding为绑定给指令的对象
        let width = '', height = '';
        function isReize() {
            const style = document.defaultView.getComputedStyle(el);
            if (width !== style.width || height !== style.height) {
                binding.value();  
            }
            width = style.width;
            height = style.height;
        }
        el.__vueSetInterval__ = setInterval(isReize, 300);
    },
    unmounted(el){
        clearInterval(el.__vueSetInterval__);
    }
})
<div class="chart-container" v-resize="eresize"><BudgetChart :chartData="ocrfData" :resize="resize"/></div>
<script>
function eresize() {
   if (resize.value) {
     resize.value = false;
   } else {
     resize.value = true;
   }
 }
</script>

二.元素拖拽 v-drag(不限制)

拖动元素换位置,适用于弹出类型的信息;
可根据使用元素的定位类型限制拖拽范围;

app.directive('drag', {
   mounted(el, binding) { // el为绑定的元素,binding为绑定给指令的对象
       el.onmousedown = function(e){
           // var disx = e.clientX - el.offsetLeft;
           // var disy = e.clientY - el.offsetTop;
           var disx = e.pageX - el.offsetLeft;
           var disy = e.pageY - el.offsetTop;
           let bottomY=document.documentElement.clientHeight
           // let bottomY=document.documentElement.clientHeight - el.offsetHeight
           // let leftX=document.documentElement.clientWidth - el.offsetWidth
           document.onmousemove = function (e){
               let top = e.clientY - disy;
               let left = e.clientX - disx;
               el.style.left = e.pageX - disx+'px';
               // el.style.top = e.pageY - disx+'px';
               // el.style.left =(left>0&&left<leftX)?left+'px':left<=0?0:leftX+'px'
               el.style.top = (top>0&&top<bottomY)?top+'px':top<=0?0:bottomY+'px' 
               // el.style.top = (top>0&&top<bottomY)?top+'px':bottomY+'px' 
           }
           document.onmouseup = function(){
               document.onmousemove = document.onmouseup = null;
           }
       }
   }
 })
<div class="discussion" v-drag :style="'top:'+ divTop"></div>
<style>
.discussion{
  width: 36%;
  height: 586px;
  background-color: #f6f7fb;
  position: fixed;
  top: 102px;
  z-index: 999;
  left: 4%;
  border-radius: 4px;
  box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.25);
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值