vue中 拖動元素邊框 改變元素寬度


先上效果圖:

如圖所示,通過拖動來改變表單的寬度。

但實際上,這邊並不是表單的邊框,而是一個單獨的組件。通過監聽鼠標的down,move以及up事件。

我們可以單獨的寫個組件handle.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將值傳給父組件,父組件通過傳過來的值來動態的修改需要改變寬度的元素。

如效果圖所示,寫一個有需求組件,並引入handle組件

<div class='sss'>    
  <div  :style="{ width: width + 'px' }" ></div> // 這里是你自己需要改變寬度的組件
  <XHandle class="myxhandle" @widthChange="widthChange" />
</div>
<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。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM