星星評分功能(帶小數點的那種,5顆星,10分制)
阿新 • • 發佈:2020-12-15
描述:
做一個星星評分功能,5顆星,10分制,精確到小數點的那種。
可以封裝成元件,哪裡需要就引入到需要的介面即可。
//score.vue
//html程式碼
<view class="scroe-content">
<template v-if="score>0">
<text>顯示從父元件傳遞過來的分數{{(score/10).toFixed(2)}}</text>
<template v-for="(item,index) in fullStar" >
<view class="star-one" :key="index">
<view class="star-two">
<view class="star" :style="{'width':item.width}"></view>
</view>
</view>
</template>
<tempalte v-if="greyStar">
<image src="這裡放灰色星星" class="star-img" v-for="item in greyStar" :key="item"></image>
</template>
</template>
<template v-else>
//這裡放灰色星星,迴圈 greyStar 變數即可
<image src="這裡放灰色星星" class="star-img" v-for="item in greyStar" :key="item"></image>
</template>
</view>
//js
export default {
props:{
score:{}
},
data(){
return{
greyStar:0,
fullStar:[],
}
},
mounted(){
this.isFullStar();
},
methods:{
isFullStar(){
let score = (this.score / 10) / 2 ;
let score_int = parseInt(score);
let fullStar = [];
for(let i=0;i<score_int;i++){
fullStar.push({
width:'100%'
})
}
let score_float = score.toFixed(2);
let float = '0.' + score_float.split('.')[1];
if(float == 0 && this.score%2===0){
}else{
let float_width = Number(float) * 100;
fullStar.push({
width:float_width + '%'
})
}
this.greyStar = 5 - fullStar.length;
this.fullStar = fullStar
}
}
}
//css
.score-content{
display:flex;
justify-content:center;
align-items:center
}
.star-img{
width:25rpx;
height:25rpx;
}
.star-one,.star-two{
width:25rpx;
height:25rpx
}
.star-one{
position:relative;
background:url('放灰色星星') no-repeat;
background-size:cover;
margin-right:7rpx;
}
.star{
position:absolute;
top:0;
left:0;
width:70%;
height:25rpx;
background:url('放亮星星') no-repeat;
background-size:cover;
}
//使用方式,假設index介面需要使用
//js
import score from '@/components/score.vue;
components:{
score
}
//html--假設是在迴圈裡面
<score :score="item.score"></score>
參考連結:https://www.jb51.net/article/113960.htm