🐙

サイズ調整可能なパネル | Vue3(Options API)

に公開

概要

画面の下部に前面表示したエリアの上部をドラッグすることで、エリアの高さを調整できるようにしたいことがあった。Window の高さが最大の高さである。ResizablePanel.vue というコンポーネントを実装して、スロットアイテムを内包する。

実装

Template

<div class="resizable-panel" :style="{ height: panelHeight + 'px' }">
    <div class="drag-handle" @mousedown.prevent="startDrag">
      <div class="handle-bar"></div>
    </div>
    <div class="panel-content">
      <slot></slot>
    </div>
</div>

JavaScript

export default {
  name: 'ResizablePanel',
  props: {
    // 初期高さ
    initialHeight: {
      type: Number,
      default: 200,
    },
    // 最小の高さ
    minHeight: {
      type: Number,
      default: 100,
    },
    // 最大の高さ
    maxHeight: {
      type: Number,
      default: 800, // デフォルトをウィンドウ高さを考慮して大きめに変更
    },
    // (変更点) Window上部に残すマージン
    topMargin: {
      type: Number,
      default: 50, // デフォルト50px
    },
  },
  data() {
    return {
      panelHeight: this.initialHeight,
      isDragging: false,
      startY: 0,
      startHeight: 0,
    };
  },
  methods: {
    startDrag(event) {
      this.isDragging = true;
      this.startY = event.clientY;
      this.startHeight = this.panelHeight;

      window.addEventListener('mousemove', this.doDrag);
      window.addEventListener('mouseup', this.stopDrag);
    },

    // (変更点) doDragメソッドの最大高さロジックを変更
    doDrag(event) {
      if (!this.isDragging) return;

      const deltaY = event.clientY - this.startY;
      let newHeight = this.startHeight - deltaY; // 上にドラッグで高く

      // 最小高さの制限 (Props.minHeight)
      if (newHeight < this.minHeight) {
        newHeight = this.minHeight;
      }

      // Windowの高さに基づく最大値
      const windowMaxHeight = window.innerHeight - this.topMargin;

      // PropsのmaxHeightとWindowの高さに基づく最大値の「小さい方」を上限とする
      const effectiveMaxHeight = Math.min(this.maxHeight, windowMaxHeight);

      if (newHeight > effectiveMaxHeight) {
        newHeight = effectiveMaxHeight;
      }

      this.panelHeight = newHeight;
    },
    
    stopDrag() {
      if (!this.isDragging) return;
      
      this.isDragging = false;
      window.removeEventListener('mousemove', this.doDrag);
      window.removeEventListener('mouseup', this.stopDrag);
    },
  },
  beforeUnmount() {
    this.stopDrag();
  },
};

CSS(SCSS)

.resizable-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #f0f0f0;
  border-top: 1px solid #ccc;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.drag-handle {
  width: 100%;
  padding: 4px 0;
  cursor: ns-resize;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e0e0e0;
  flex-shrink: 0;
}

.handle-bar {
  width: 40px;
  height: 4px;
  background-color: #aaa;
  border-radius: 2px;
}

.panel-content {
  padding: 15px;
  flex-grow: 1;
  overflow-y: auto;
}

Discussion