| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <template>
- <view class="sr-wrap">
- <view class="sr-row">
- <text
- v-for="s in stars"
- :key="s.index"
- class="sr-star"
- :class="s.cls"
- @click="handleTap(s.index)"
- >★</text>
- </view>
- <text v-if="showValue" class="sr-value">{{ valueText }}</text>
- </view>
- </template>
- <script>
- /**
- * StarRating — 星级组件(原子级:1-5 星,只读/提交双模式)
- * 说明:
- * - 需求明确「半颗不用」,只读沿用整数星:value=4.7 → 5 星满;value=4.2 → 4 星满
- * (四舍五入,展示「★x5」+ 数字文本给精确值,避免误导)
- * - 提交模式:点选 1-5,emit input
- * 用法(只读):<StarRating :value="4.7" :show-value="true" readonly />
- * 用法(提交):<StarRating :value="score" :readonly="false" @input="score = $event" />
- */
- export default {
- name: 'StarRating',
- props: {
- // 当前星级:只读 0-5 小数;提交 1-5 整数
- value: { type: Number, default: 0 },
- readonly: { type: Boolean, default: true },
- showValue: { type: Boolean, default: false }
- },
- data() {
- return {
- picked: 0
- }
- },
- computed: {
- stars() {
- var arr = []
- var filled = this.readonly ? this.roundValue() : this.picked
- for (var i = 1; i <= 5; i++) {
- arr.push({
- index: i,
- cls: i <= filled ? 'sr-filled' : 'sr-empty'
- })
- }
- return arr
- },
- valueText() {
- if (!this.showValue) return ''
- var v = this.value || 0
- // 后端评分已 round2(2 位小数),展示保留 2 位保持一致
- return v > 0 ? v.toFixed(2) : '—'
- }
- },
- watch: {
- // 父级传入的值更新时同步本地选择(提交模式初始化)
- value: {
- immediate: true,
- handler(val) {
- this.picked = val || 0
- }
- }
- },
- methods: {
- roundValue() {
- var v = this.value || 0
- if (v <= 0) return 0
- return Math.round(v)
- },
- handleTap(idx) {
- if (this.readonly) return
- this.picked = idx
- this.$emit('input', idx)
- }
- }
- }
- </script>
- <style scoped>
- .sr-wrap {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- .sr-row {
- display: flex;
- }
- .sr-star {
- font-size: 44rpx;
- margin: 0 6rpx;
- line-height: 1;
- }
- .sr-filled { color: #B9770E; }
- .sr-empty { color: #DCE7F1; }
- .sr-value {
- font-size: 24rpx;
- color: #3B5A78;
- margin-top: 8rpx;
- }
- </style>
|