vue.js 如果有多个组件,则组件无法正常工作

mwkjh3gx  于 2023-10-23  发布在  Vue.js
关注(0)|答案(1)|浏览(177)

我在Vue中有以下组件:

<script setup lang="ts">
  import { PropType } from "nuxt/dist/app/compat/capi";
  interface Star {
    id: string;
    value: number;
  }

  const stars: Star[] = [
    { id: "star5", value: 5 },
    { id: "star4.5", value: 4.5 },
    { id: "star4", value: 4 },
    { id: "star3.5", value: 3.5 },
    { id: "star3", value: 3 },
    { id: "star2.5", value: 2.5 },
    { id: "star2", value: 2 },
    { id: "star1.5", value: 1.5 },
    { id: "star1", value: 1 },
    { id: "star0.5", value: 0.5 },
  ];

  const props = defineProps({
    ratingValue: {
      type: Number as PropType<number>,
    },
    starColor: {
      type: String as PropType<string>,
    },
  });

  const emit = defineEmits(["ratingChange"]);
  const selectedRating = ref<number | undefined>(undefined);

  const roundedRating = computed(() => {
    if (props.ratingValue !== undefined) {
      return Math.round(props.ratingValue * 2) / 2;
    } else {
      return selectedRating.value !== undefined
        ? Math.round(selectedRating.value * 2) / 2
        : undefined;
    }
  });

  const onRatingChange = (value: number) => {
    if (props.ratingValue === undefined) {
      selectedRating.value = value;
      emit("ratingChange", selectedRating.value);
    }
  };
</script>

<template>
  <div class="center">
    <div :class="['rating', { disable: props.ratingValue !== undefined }]">
      <template v-for="star in stars" :key="star.id">
        <input
          :id="star.id"
          v-model="roundedRating"
          :disabled="props.ratingValue !== undefined"
          type="radio"
          name="'rating'"
          :value="star.value"
          @input="onRatingChange(star.value)"
        />
        <label :for="star.id" :class="star.value % 1 === 0 ? 'full full-star' : 'half'"></label>
      </template>
    </div>
    <div class="rating-number">{{ props.ratingValue }}</div>
  </div>
</template>

如果它只在页面上使用一次,那么它就可以正常工作,但是如果有一个以上的,那么它就有点坏了。
如果指定ratingValue,则显示右侧的数字,但应在两个组件中绘制的星星仅在最后一个组件中绘制。

<StarRating ratingValue="1" />
<StarRating ratingValue="4" />

我试图弄清楚它,我认为问题是与selectedRating,但我试图修复它是不成功的

wdebmtf2

wdebmtf21#

你必须有唯一的name属性,你可以这样实现它:
脚本:

import { ref } from 'vue';

const uniqueId = ref(Date.now() + Math.random().toString(36).substr(2, 9));

模板(T):

<input
  :id="star.id"
  v-model="roundedRating"
  :disabled="props.ratingValue !== undefined"
  type="radio"
  :name="`rating-${uniqueId}`"
  :value="star.value"
  @input="onRatingChange(star.value)"
/>

相关问题