<template>
<view class="pjdd">
<image v-for="(star, index) in stars" :key="index" :src="star.isSelected ? selectedStarSrc : unselectedStarSrc" @click="toggleStar(index)"/>
</view>
</template>
<script>
export default {
data() {
return {
selectedStarSrc: '/static/star-selected.png', // 已点亮的图片路径
unselectedStarSrc: '/static/star-unselected.png', // 未点亮的图片路径
stars: [] // 初始化评分数组
};
},
created() {
// 初始化五颗评分星,都未点亮
this.stars = new Array(5).fill({ isSelected: false });
},
methods: {
toggleStar(index) {
// 切换星星的选中状态
this.stars = this.stars.map((star, i) => ({
isSelected: i <= index
}));
}
}
};
</script>
<style>
.pjdd image { width: 40rpx; height: 40rpx; margin: 0 5px; cursor: pointer;}
</style>
方法二:
<view class="pjdd">
<image v-for="(item, index) in 5" :key="index" :src="getStarSrc(index)" class="star-image" @click="toggleStar(index)" />
</view>
<script>
export default {
data() {
return {
selectedIndex: 0, // 默认没有星星被选中
}
},
methods: {
getStarSrc(index) {
// 根据是否被选中返回不同的图片地址
return this.selectedIndex >= index ? '/static/images/pjxx2.png' : '/static/images/pjxx1.png';
},
toggleStar(index) {
// 点亮或灭掉图片时更新selectedIndex
this.selectedIndex = index;
},
}
}
</script>