vue2.0+stylus实现星级评定组件,computed计算属性实现全星半星,多种星星规格
使用方法如下:(size为星星的大小,score为评分,比如传4.5,则4.5颗星亮;传4.1则四颗星亮)
<div class="score-wrapper">
<span class="title">服务态度</span>
<star :size="36" :score="3.5"></star>
<span class="score">3.5</span>
</div>
<div class="score-wrapper">
<span class="title">商品评分</span>
<star :size="36" :score="4.1"></star>
<span class="score">4.1</span>
</div>
效果:
以下为star.vue实现代码
template:<template>
<div class="star" :class="starType">
<span v-for="itemClass in itemClasses" :class="itemClass" class="star-item"></span>
</div>
</template>
<script type="text/ecmascript-6">
// 评分有几个等级
const LENGTH = 5;
// 全星有几个
const CLS_ON = 'on';
// 半星有几个
const CLS_HALF = 'half';
// 不亮的星星有几个
const CLS_OFF = 'off';
export default {
props: {
// 图片尺寸
size: {
type: Number
},
// 评分
score: {
type: Number
}
},
computed: {
// 显示对应尺寸的星星图片, 比如size是48,则添加star-48类,显示对应样式
starType() {
return 'star-' + this.size;
},
// 包含
itemClasses() {
let result = [];
// 分数取整
let score = Math.floor(this.score * 2) / 2;
// 判断是否有半星
let hasDecimal = score % 1 !== 0;
// 计算有几个全星
let integer = Math.floor(score);
for (let i = 0; i < integer; i++) {
result.push(CLS_ON);
}
if (hasDecimal) {
result.push(CLS_HALF);
}
while (result.length < LENGTH) {
result.push(CLS_OFF);
}
return result;
}
}
};
</script>
style:(本人使用的是stylus,功能类似sass、less等)
<style lang="stylus" rel="stylus/stylesheet">
@import "../../common/stylus/mixin.styl"
.star
font-size 0
.star-item
display inline-block
&.star-48
.star-item
width 20px
height 20px
margin-right 22px
&:last-child
margin-right 0
&.on
bg-image('star48_on',20px,20px,no-repeat)
&.half
bg-image('star48_half',20px,20px,no-repeat)
&.off
bg-image('star48_off',20px,20px,no-repeat)
&.star-36
.star-item
width 15px
height 15px
margin-right 6px
&:last-child
margin-right 0
&.on
bg-image('star48_on',15px,15px,no-repeat)
&.half
bg-image('star48_half',15px,15px,no-repeat)
&.off
bg-image('star48_off',15px,15px,no-repeat)
&.star-24
.star-item
width 10px
height 10px
margin-right 3px
&:last-child
margin-right 0
&.on
bg-image('star48_on',10px,10px,no-repeat)
&.half
bg-image('star48_half',10px,10px,no-repeat)
&.off
bg-image('star48_off',10px,10px,no-repeat)
</style>
其中 bg-image函数写在mixin.stylus中,通过以下方法引入使用
@import "../../common/stylus/mixin.styl"
bg-image函数的代码为:(实现背景图片的选择,图片大小的设置、是否重复等功能)
bg-image($url,$width,$height,$repeat)
@media (-webkit-max-device-pixel-ratio: 2),(max-device-pixel-ratio: 2)
background-image url($url + "@2x.png")
background-size $width $height
background-repeat $repeat
@media (-webkit-min-device-pixel-ratio: 3),(min-device-pixel-ratio: 3)
background url($url + "@3x.png")
background-size $width $height
background-repeat $repeat
使用到的图片,以下为size为36px的@2x图片。
star36_on@2x.png
star36_half@2x.png
star36_off@2x.png