使用vue3实现简单的滑块组件,实现了基本的滑块功能和交互行为。

滑块组件主要是利用鼠标事件,让滑块跟着鼠标跟着x轴动,效果如下。

创建了一个名为 CustomSlider 的自定义滑块组件。它接受 minmaxstep 作为 props,用于设置滑块的取值范围和步长。使用 emits 属性声明了一个名为 update:modelValue 的自定义事件,用于向父组件发送滑块值的更新。

yaml 复制代码
name: 'CustomSlider',
props: { min: { type: Number, default: 0 }, 
    max: { type: Number, default: 100 }, 
    step: { type: Number, default: 1 } },
emits: ['update:modelValue'],

setup 函数中,我们使用了 Vue 3 的组合式 API 来定义滑块组件的逻辑。我们使用了 ref 来创建了 thumbPositionisDragging 两个响应式变量。thumbPosition 用于控制滑块的位置,isDragging 用于标记是否正在拖动滑块。

通过计算属性 trackWidth,我们根据最小值和最大值计算出滑块轨道的宽度,用于动态设置样式。

ini 复制代码
   const thumbPosition = ref('0%');
    const isDragging = ref(false);

    const trackWidth = computed(() => {
      const range = props.max - props.min;
      return `${(100 * range) / (props.max - props.min)}%`;
    });

startDrag 方法中,我们监听了滑块的鼠标按下事件,并在按下时开始拖动操作。在 handleDrag 方法中,我们根据鼠标位置计算出滑块的值,并通过 emit 方法触发 update:modelValue 事件,将滑块的值发送给父组件。

ini 复制代码
 const startDrag = (event) => {
      isDragging.value = true;
      document.addEventListener('mousemove', handleDrag);
      document.addEventListener('mouseup', stopDrag);
    };

    const handleDrag = (event) => {
      if (isDragging.value) {
        const sliderWidth = event.target.parentNode.offsetWidth;
        const offsetX = event.pageX - event.target.parentNode.offsetLeft;
        const percentage = (offsetX / sliderWidth) * 100;
        const value = (percentage * (props.max - props.min)) / 100 + props.min;
        const snappedValue = Math.round(value / props.step) * props.step;
        const clampedValue = Math.max(props.min, Math.min(props.max, snappedValue));
        thumbPosition.value = `${((clampedValue - props.min) / (props.max - props.min)) * 100}%`;
        emit('update:modelValue', clampedValue);
      }
    };

    const stopDrag = () => {
      isDragging.value = false;
      document.removeEventListener('mousemove', handleDrag);
      document.removeEventListener('mouseup', stopDrag);
    };

onMountedonUnmounted 钩子中,我们分别添加和移除了监听鼠标抬起事件的事件处理函数,以确保在组件销毁时正确清理事件监听器。

javascript 复制代码
  onMounted(() => {
      document.addEventListener('mouseup', stopDrag);
    });

    onUnmounted(() => {
      document.removeEventListener('mouseup', stopDrag);
    });

完整代码如下:

xml 复制代码
<template>
  <div class="slider">
    <div class="track" :style="{ width: trackWidth }"></div>
    <div class="thumb" :style="{ left: thumbPosition }" @mousedown="startDrag"></div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';

export default {
  name: 'CustomSlider',
  props: {
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: 100
    },
    step: {
      type: Number,
      default: 1
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const thumbPosition = ref('0%');
    const isDragging = ref(false);

    const trackWidth = computed(() => {
      const range = props.max - props.min;
      return `${(100 * range) / (props.max - props.min)}%`;
    });

    const startDrag = (event) => {
      isDragging.value = true;
      document.addEventListener('mousemove', handleDrag);
      document.addEventListener('mouseup', stopDrag);
    };

    const handleDrag = (event) => {
      if (isDragging.value) {
        const sliderWidth = event.target.parentNode.offsetWidth;
        const offsetX = event.pageX - event.target.parentNode.offsetLeft;
        const percentage = (offsetX / sliderWidth) * 100;
        const value = (percentage * (props.max - props.min)) / 100 + props.min;
        const snappedValue = Math.round(value / props.step) * props.step;
        const clampedValue = Math.max(props.min, Math.min(props.max, snappedValue));
        thumbPosition.value = `${((clampedValue - props.min) / (props.max - props.min)) * 100}%`;
        emit('update:modelValue', clampedValue);
      }
    };

    const stopDrag = () => {
      isDragging.value = false;
      document.removeEventListener('mousemove', handleDrag);
      document.removeEventListener('mouseup', stopDrag);
    };

    onMounted(() => {
      document.addEventListener('mouseup', stopDrag);
    });

    onUnmounted(() => {
      document.removeEventListener('mouseup', stopDrag);
    });

    return {
      thumbPosition,
      trackWidth,
      startDrag
    };
  }
};
</script>

<style>
.slider {
  position: relative;
  width: 100%;
  height: 10px;
  background-color: #ccc;
}

.track {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: #409eff;
}

.thumb {
  position: absolute;
  top: -5px;
  left: 0;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #409eff;
  cursor: pointer;
}
</style>
相关推荐
Mr Xu_9 分钟前
Vue 3 中 watch 的使用详解:监听响应式数据变化的利器
前端·javascript·vue.js
未来龙皇小蓝12 分钟前
RBAC前端架构-01:项目初始化
前端·架构
程序员agions21 分钟前
2026年,微前端终于“死“了
前端·状态模式
万岳科技系统开发21 分钟前
食堂采购系统源码库存扣减算法与并发控制实现详解
java·前端·数据库·算法
程序员猫哥_29 分钟前
HTML 生成网页工具推荐:从手写代码到 AI 自动生成网页的进化路径
前端·人工智能·html
龙飞0529 分钟前
Systemd -systemctl - journalctl 速查表:服务管理 + 日志排障
linux·运维·前端·chrome·systemctl·journalctl
我爱加班、、34 分钟前
Websocket能携带token过去后端吗
前端·后端·websocket
AAA阿giao34 分钟前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
杨超越luckly41 分钟前
HTML应用指南:利用GET请求获取中国500强企业名单,揭秘企业增长、分化与转型的新常态
前端·数据库·html·可视化·中国500强
一 乐1 小时前
校园二手交易|基于springboot + vue校园二手交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端