当前位置:首页 > VUE

vue实现等级选择

2026-01-14 01:19:45VUE

Vue 实现等级选择的方法

使用 v-for 渲染等级选项

通过 v-for 循环生成等级选项,结合 v-model 实现双向绑定。

<template>
  <div>
    <div v-for="n in 5" :key="n" @click="selectLevel(n)">
      <span :class="{ 'active': n <= selectedLevel }">★</span>
    </div>
    <p>当前选择: {{ selectedLevel }}星</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedLevel: 0
    }
  },
  methods: {
    selectLevel(level) {
      this.selectedLevel = level
    }
  }
}
</script>

<style>
.active {
  color: gold;
}
</style>

使用第三方组件

可以集成现成的评分组件如 vue-star-rating:

npm install vue-star-rating
<template>
  <star-rating v-model="rating" :increment="0.5" :star-size="30"/>
</template>

<script>
import StarRating from 'vue-star-rating'

export default {
  components: {
    StarRating
  },
  data() {
    return {
      rating: 3
    }
  }
}
</script>

自定义 SVG 图标

使用 SVG 实现更灵活的样式控制:

<template>
  <div class="rating-container">
    <svg v-for="i in 5" :key="i" @click="setRating(i)" width="24" height="24">
      <polygon 
        :points="getStarPoints(12, 12, 10, i)" 
        :fill="i <= currentRating ? '#FFD700' : '#DDD'"
      />
    </svg>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentRating: 0
    }
  },
  methods: {
    setRating(rating) {
      this.currentRating = rating
    },
    getStarPoints(cx, cy, r, n) {
      // 生成五角星坐标点的算法
    }
  }
}
</script>

结合 Element UI 组件

如果使用 Element UI 框架:

vue实现等级选择

<template>
  <el-rate v-model="value" :colors="colors" :texts="texts" show-text/>
</template>

<script>
export default {
  data() {
    return {
      value: null,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      texts: ['差', '一般', '好']
    }
  }
}
</script>

注意事项

  • 移动端需考虑触摸事件处理
  • 可添加半星选择功能
  • 建议提供视觉反馈(如hover效果)
  • 无障碍访问需设置aria-label属性

以上方法可根据具体需求选择或组合使用,从简单到复杂提供了多种实现方案。

标签: 等级vue
分享给朋友:

相关文章

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue实现录音文件播放

vue实现录音文件播放

使用 Vue 实现录音文件播放 准备工作 确保项目中已安装必要的依赖,如 vue-audio-recorder 或原生 Web Audio API。录音文件播放通常涉及录音、存储和播放三个核心环节。…

vue怎么实现

vue怎么实现

Vue 实现方法 Vue 是一个流行的前端框架,用于构建用户界面。以下是几种常见的实现方法: 数据绑定 使用 v-model 指令实现双向数据绑定,适用于表单输入元素。 <input v-m…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现123456

vue实现123456

Vue 实现数字 123456 的显示 在 Vue 中显示数字 123456 非常简单,可以通过以下方法实现: 方法一:直接在模板中显示 <template> <div>…

vue实现tooltips

vue实现tooltips

Vue 实现 Tooltips 的方法 使用原生 HTML title 属性 在 Vue 模板中直接使用 HTML 原生 title 属性实现简单的提示效果。这种方式无需额外依赖,但功能较为基础,无法…