最近在学习vue,制作一个排名组件。
为了使其正常工作,我需要一一显示元素,如示例所示:
<input type="text">
<label for=""></label>
<input type="text">
<label for=""></label>
<input type="text">
<label for=""></label>
但是我的代码显然首先绘制输入,然后绘制标签:
<script setup>
const stars = [
{ 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 },
];
</script>
<template>
<div class="center">
<div class="rating">
<input
type="radio"
v-for="star in stars"
:key="star.value"
:id="star.id"
:name="'rating'"
:value="star.value"
/>
<label
v-for="star in stars"
:key="star.value"
:for="star.id"
:class="[star.value % 1 === 0 ? 'full' : 'half']"
></label>
</div>
</div>
</template>
我尝试用不同的方式画星星,就像这样:
<div class="center">
<fieldset class="rating">
<div v-for="star in stars" :key="star.id">
<input type="radio" :id="star.id" :name="'rating'" :value="star.value" />
<label :for="star.id" :class="[star.value % 1 === 0 ? 'full' : 'half']"></label>
</div>
</fieldset>
</div>
但是在这种情况下,添加了额外的一半,并且元素没有发挥应有的作用。
如何按照我在示例中所示的那样,一一绘制元素?
进行更改,使标签标签包裹输入,并从输入标签 is 中删除第二个 v-for。
注意
</label>
标签所在的位置:
<div class="center">
<div class="stars">
<label
v-for="star in stars"
:key="star.value"
:for="star.id"
:class="star.value % 1 === 0 ? 'full' : 'half'"
>
<input
type="radio"
:key="star.value"
:id="star.id"
:name="'rating'"
:value="star.value"
/>
</label>
</div>
</div>