Vue星级评分实现:悬停时高亮当前及之前的评分项
Vue 五星评分悬停高亮实现方案
模板实现
通过v-for循环渲染评分圆点,绑定鼠标事件与动态类名,同步记录每个项的索引:
<template> <div class="rating-container"> <div v-for="(item, index) in ratingsArray" :key="index" class="rating-box" :class="{ 'ratingBoxChecked': index <= hoverIndex || item.isEnabled }" @mouseenter="handleMouseEnter(index)" @mouseleave="handleMouseLeave" @click="handleRatingClick(index)" > <!-- 可自定义添加图标/文字,此处以圆点为基础示例 --> </div> </div> </template>
脚本逻辑
定义响应式变量跟踪悬停索引,配合已有ratingsArray实现点击选中与悬停高亮逻辑:
<script setup> import { ref } from 'vue' // 初始化5个评分项的数组 const ratingsArray = ref([ { name: '评分1', ratingValue: 1, isEnabled: false }, { name: '评分2', ratingValue: 2, isEnabled: false }, { name: '评分3', ratingValue: 3, isEnabled: false }, { name: '评分4', ratingValue: 4, isEnabled: false }, { name: '评分5', ratingValue: 5, isEnabled: false } ]) // 记录当前悬停的圆点索引,初始-1表示无悬停状态 const hoverIndex = ref(-1) // 鼠标进入圆点时更新悬停索引 const handleMouseEnter = (index) => { hoverIndex.value = index } // 鼠标离开评分容器时重置悬停索引 const handleMouseLeave = () => { hoverIndex.value = -1 } // 点击圆点时更新选中状态 const handleRatingClick = (index) => { // 先重置所有项的选中状态 ratingsArray.value.forEach(item => item.isEnabled = false) // 将当前圆点及之前的所有项设为选中 for (let i = 0; i <= index; i++) { ratingsArray.value[i].isEnabled = true } } </script>
样式处理
添加基础圆点样式与高亮样式,实现视觉反馈:
<style scoped> .rating-container { display: flex; gap: 8px; } .rating-box { width: 24px; height: 24px; border-radius: 50%; background-color: #e0e0e0; cursor: pointer; transition: background-color 0.2s; } .ratingBoxChecked { background-color: #ffc107; /* 可自定义高亮颜色 */ } </style>
核心逻辑说明
- 悬停效果:通过
hoverIndex记录当前鼠标停留位置,动态类名判断index <= hoverIndex,实现当前及之前圆点的批量高亮 - 点击效果:点击时先重置所有项的
isEnabled状态,再将当前索引及之前的项设为true,实现选中后的持久高亮 - 离开重置:鼠标离开后
hoverIndex归位,仅保留已选中的高亮状态
内容的提问来源于stack exchange,提问作者mikasa
相关产品推荐
相关产品推荐

