star-rating.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <template>
  2. <view class="sr-wrap">
  3. <view class="sr-row">
  4. <text
  5. v-for="s in stars"
  6. :key="s.index"
  7. class="sr-star"
  8. :class="s.cls"
  9. @click="handleTap(s.index)"
  10. >★</text>
  11. </view>
  12. <text v-if="showValue" class="sr-value">{{ valueText }}</text>
  13. </view>
  14. </template>
  15. <script>
  16. /**
  17. * StarRating — 星级组件(原子级:1-5 星,只读/提交双模式)
  18. * 说明:
  19. * - 需求明确「半颗不用」,只读沿用整数星:value=4.7 → 5 星满;value=4.2 → 4 星满
  20. * (四舍五入,展示「★x5」+ 数字文本给精确值,避免误导)
  21. * - 提交模式:点选 1-5,emit input
  22. * 用法(只读):<StarRating :value="4.7" :show-value="true" readonly />
  23. * 用法(提交):<StarRating :value="score" :readonly="false" @input="score = $event" />
  24. */
  25. export default {
  26. name: 'StarRating',
  27. props: {
  28. // 当前星级:只读 0-5 小数;提交 1-5 整数
  29. value: { type: Number, default: 0 },
  30. readonly: { type: Boolean, default: true },
  31. showValue: { type: Boolean, default: false }
  32. },
  33. data() {
  34. return {
  35. picked: 0
  36. }
  37. },
  38. computed: {
  39. stars() {
  40. var arr = []
  41. var filled = this.readonly ? this.roundValue() : this.picked
  42. for (var i = 1; i <= 5; i++) {
  43. arr.push({
  44. index: i,
  45. cls: i <= filled ? 'sr-filled' : 'sr-empty'
  46. })
  47. }
  48. return arr
  49. },
  50. valueText() {
  51. if (!this.showValue) return ''
  52. var v = this.value || 0
  53. // 后端评分已 round2(2 位小数),展示保留 2 位保持一致
  54. return v > 0 ? v.toFixed(2) : '—'
  55. }
  56. },
  57. watch: {
  58. // 父级传入的值更新时同步本地选择(提交模式初始化)
  59. value: {
  60. immediate: true,
  61. handler(val) {
  62. this.picked = val || 0
  63. }
  64. }
  65. },
  66. methods: {
  67. roundValue() {
  68. var v = this.value || 0
  69. if (v <= 0) return 0
  70. return Math.round(v)
  71. },
  72. handleTap(idx) {
  73. if (this.readonly) return
  74. this.picked = idx
  75. this.$emit('input', idx)
  76. }
  77. }
  78. }
  79. </script>
  80. <style scoped>
  81. .sr-wrap {
  82. display: flex;
  83. flex-direction: column;
  84. align-items: center;
  85. }
  86. .sr-row {
  87. display: flex;
  88. }
  89. .sr-star {
  90. font-size: 44rpx;
  91. margin: 0 6rpx;
  92. line-height: 1;
  93. }
  94. .sr-filled { color: #B9770E; }
  95. .sr-empty { color: #DCE7F1; }
  96. .sr-value {
  97. font-size: 24rpx;
  98. color: #3B5A78;
  99. margin-top: 8rpx;
  100. }
  101. </style>