vue3实现拖拽线

效果图:

 

 实现代码:

<template>
  <div class="main">
    <div class="left" :style="{ width: left_width + 'px' }">left</div>
    <div class="dragLine" :style="{ width: dragLine_width + 'px' }"></div>
    <div class="right" :style="{ width: right_width + 'px' }">right</div>
  </div>
</template>
<script setup>
import { ref } from "vue";

const current_width = ref(200);

const left_width = computed(() => {
  return current_width.value;
});
const dragLine_width = ref(5);
const right_width = computed(() => {
  return window.innerWidth - current_width.value - dragLine_width.value;
});
const isTarget = ref(false);

const mousedown = (event) => {
  const targetDom = event.target;
  if (targetDom.className === "dragLine") {
    isTarget.value = true;
    event.preventDefault();
    event.stopPropagation();
  } else {
    isTarget.value = false;
  }
};
const mouseMove = (event) => {
  if (isTarget.value) {
    current_width.value = event.x;
    event.preventDefault();
    event.stopPropagation();
  }
};
const mouseUp = (event) => {
  isTarget.value = false;
  event.preventDefault();
  event.stopPropagation();
};
onMounted(() => {
  document.addEventListener("mousedown", mousedown);
  document.addEventListener("mousemove", mouseMove);
  document.addEventListener("mouseup", mouseUp);
});

onUnmounted(() => {
  document.removeEventListener("mousedown", mousedown);
  document.removeEventListener("mousemove", mouseMove);
  document.removeEventListener("mouseup", mouseUp);
});
</script>
<style lang="scss" scoped>
.main {
  background-color: rgb(228, 228, 228);
  width: 100vw;
  height: 100vh;
  display: flex;
  overflow: hidden;
  .left {
    height: 100%;
    min-width: 100px;
    background-color: aquamarine;
  }
  .dragLine {
    height: 100%;
    background-color: rgb(0, 183, 255);
    cursor: w-resize;
    &:hover {
      background-color: rgb(0, 102, 255);
    }
  }
  .right {
    height: 100%;
    min-width: 100px;

    background-color: bisque;
  }
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/130726710