vue3 实现滑动调整宽度的效果

时间:2024-03-24 12:27:59
export default defineComponent({
  data() {
    return {
      collapsed: false,
      sidebarWidth: 200,
      resizing: false,
      startX: 0,
      startWidth: 200,
      moveHandler: null as null | ((event: MouseEvent) => void),
    };
  },
  methods: {
    startResize(event: MouseEvent) {
      this.resizing = true;
      this.startX = event.clientX;
      this.startWidth = this.sidebarWidth;
      this.moveHandler = this.resize.bind(this);
      document.addEventListener('mousemove', this.moveHandler);
      document.addEventListener('mouseup', this.stopResize);
    },
    resize(event: MouseEvent) {
      if (this.resizing) {
        const deltaX = event.clientX - this.startX;
        this.sidebarWidth = Math.max(this.startWidth + deltaX, 100);
      }
    },
    stopResize() {
      this.resizing = false;
      document.removeEventListener('mousemove', this.moveHandler!);
      document.removeEventListener('mouseup', this.stopResize);
      this.moveHandler = null;
      window.getSelection()?.removeAllRanges();
    },
  },
});
</script>