vue中拖动元素边框 改变元素宽度-实例

22 篇文章 2 订阅

我们可以做一个单独的组件,通过监听鼠标的down,move以及up事件来实现拖动边框,改变元素宽度功能。

下面我们写一个组件Xhandle.vue。

<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将值传给父组件,父组件通过传过来的值来动态的修改需要改变宽度的元素。

如效果图所示,写一个有需求组件,并引入Xhandle组件

<template>
<div class='sss'>    
  <div  :style="{ width: width + 'px' }" ></div> // 这里是你自己需要改变宽度的组件
  <XHandle class="myxhandle" @widthChange="widthChange" />
</div>
</template>

<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。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值