以下是一个简单的示例,展示如何使用 Vue3 实现上下两个组件拖动分割条:

<template>
  <div class="container">
    <div class="top" :style="topStyle" ref="top"></div>
    <div class="divider" @mousedown="startDrag"></div>
    <div class="bottom" :style="bottomStyle" ref="bottom"></div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'

export default {
  setup() {
    const container = ref(null)
    const top = ref(null)
    const bottom = ref(null)
    const dragging = reactive({
      active: false,
      startY: 0,
      startHeight: 0
    })

    const startDrag = e => {
      dragging.active = true
      dragging.startY = e.clientY
      dragging.startHeight = top.value.offsetHeight
    }

    const stopDrag = () => {
      dragging.active = false
    }

    const handleDrag = e => {
      if (!dragging.active) return
      const delta = e.clientY - dragging.startY
      top.value.style.height = `${dragging.startHeight + delta}px`
    }

    const topStyle = { height: '50%' }
    const bottomStyle = { height: '50%' }

    return {
      container,
      top,
      bottom,
      dragging,
      startDrag,
      stopDrag,
      handleDrag,
      topStyle,
      bottomStyle
    }
  },
  mounted() {
    document.addEventListener('mousemove', this.handleDrag)
    document.addEventListener('mouseup', this.stopDrag)
  },
  unmounted() {
    document.removeEventListener('mousemove', this.handleDrag)
    document.removeEventListener('mouseup', this.stopDrag)
  }
}
</script>

<style scoped>
.container {
  position: relative;
  height: 100%;
}

.top {
  background-color: #f0f0f0;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: auto;
  overflow: auto;
}

.divider {
  background-color: #ddd;
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 10px;
  cursor: ns-resize;
  z-index: 1;
}

.bottom {
  background-color: #f0f0f0;
  position: absolute;
  top: auto;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}
</style>

这个示例中,我们使用了 Vue3 的 refreactive 来创建一些响应式的变量。我们用 ref 来获取组件的 DOM 元素,并将其作为 ref 变量暴露给模板中的元素。我们还使用 reactive 来创建一个对象,该对象包含一个布尔值 active,以指示是否正在拖动分割条,以及鼠标位置和顶部组件的初始高度。

我们在模板中渲染了三个 div 元素,分别代表顶部组件、分割条和底部组件。我们使用 :style 绑定了顶部和底部组件的高度,这样我们就可以在拖动分割条时动态调整它们的高度。

我们在分割条元素上添加了一个 @mousedown 事件监听器,以便在用户开始拖动分割条时调用 startDrag 方法。在此方法中,我们设置了 dragging 对象的属性,以指示拖动正在进行,并记录鼠标位置和顶部组件的初始高度。

我们还添加了一个 @mouseup 事件监听器,以在用户停止拖动时调用 stopDrag 方法。在此方法中,我们将 dragging.active 设置为 false,以指示拖动已结束。

我们还添加了一个 @mousemove 事件监听器,以在用户拖动分割条时调用 handleDrag 方法。在此方法中,我们检查 dragging.active 是否为 true,以确定用户是否正在拖动分割条。如果是,我们计算鼠标位置相对于初始位置的偏移量,并将其添加到顶部组件的初始高度中,以获得新的高度。

最后,我们定义了一些 CSS 样式,以设置组件的外观和布局


原文地址: https://www.cveoy.top/t/topic/eCgB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录