当前位置:首页 > VUE

vue实现等级选择

2026-01-14 01:19:45VUE

Vue 实现等级选择的方法

使用 v-for 渲染等级选项

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

vue实现等级选择

<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:

vue实现等级选择

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 框架:

<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 SSG实现

vue SSG实现

Vue SSG 实现方法 Vue 的静态站点生成(SSG)可以通过多种工具和框架实现,以下是几种常见的方法: 使用 VuePress VuePress 是一个基于 Vue 的静态站点生成器,适合文档…

vue 实现列表

vue 实现列表

Vue 实现列表的方法 在 Vue 中实现列表通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式: 基础列表渲染 使用 v-for 指令遍历数组,渲染列表项。ite…

vue实现试卷

vue实现试卷

Vue实现试卷系统的基本思路 使用Vue.js构建试卷系统需要结合组件化开发、状态管理和后端数据交互。核心功能包括题目展示、答题逻辑、计时器和提交答案。 核心功能模块划分 试卷组件结构 试卷容器组…

vue实现ajax

vue实现ajax

Vue 中实现 AJAX 的几种方法 在 Vue 中实现 AJAX 请求可以通过原生 JavaScript 的 XMLHttpRequest、第三方库如 axios 或 fetch API 来完成。以…

vue 实现登录

vue 实现登录

Vue 实现登录功能 创建登录表单组件 在 Vue 项目中创建一个登录表单组件(如 Login.vue),包含用户名和密码输入框以及提交按钮。使用 v-model 实现双向数据绑定。 <tem…

vue实现画廊

vue实现画廊

Vue实现画廊的基本方法 使用Vue.js实现画廊功能可以通过多种方式完成,以下是一种常见的实现方案: 安装必要依赖 npm install vue-gallery --save 引入组件并注册…