Rate comp by vue2
Opened this issue · 0 comments
CocaColf commented
<template>
<div class="star-wrap">
<div
class="star-item"
v-for="(i, index) in count"
:key="index"
@mousemove="handleMouseEnter(i, $event)"
@mouseleave="handleMouseLeave(i)"
@click="handleClick(i, $event)"
:ref="`star${i}`">
<div class="star-full">
<i
class="iconfont iconfont-main"
:class="icon"
:style="getStyl(i)"
></i>
</div>
<div class="star-half" v-if="showHalfIcon(i)" >
<i
:class="icon"
class="iconfont iconfont-main"
:style="getDecimalStyl"
></i>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
value: {
type: Number,
default: 0
},
strokeColor: {
type: String,
default: 'red'
},
backgroundColor: {
type: String,
default: '#ccc'
},
count: {
type: Number,
default: 5
},
icon: {
type: String,
default: 'icon-yidongdaozu'
},
allowHalf: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
tooltips: {
type: Array,
default: () => []
},
allowClear: {
type: Boolean,
default: false
}
},
data () {
return {
score: this.value,
hoverIndex: -1,
touchHalf: false
};
},
computed: {
getDecimalStyl () {
return {
color: this.strokeColor
};
},
},
watch: {
value (val) {
this.score = val;
this.touchHalf = this.value !== Math.floor(this.value);
}
},
methods: {
showHalfIcon (i) {
return this.allowHalf &&
i - 0.5 <= this.score &&
i > this.score;
},
getStyl (i) {
return {
color: i <= this.score ? this.strokeColor : this.backgroundColor
};
},
handleMouseEnter (i, e) {
if (this.disabled) {
return;
}
if (this.allowHalf) {
this.updateTouchHalf(i, e);
// console.log(this.touchHalf)
this.score = this.touchHalf ? i - 0.5 : i;
} else {
this.score = i;
}
this.hoverIndex = i;
},
handleMouseLeave () {
if (this.disabled) {
return;
}
if (this.allowHalf) {
this.touchHalf = this.value !== Math.floor(this.value);
}
this.score = this.value;
this.hoverIndex = -1;
},
handleClick () {
if (this.disabled) {
return;
}
let clearValue = false,
emitValue = 0;
if (this.allowClear) {
clearValue = this.value === this.score;
}
/**
* 如果重置,则value重置为0
* 如果点击位置在一半,则抛出计算值
* 否则抛出全职
*/
emitValue = clearValue ? 0 :
// (this.allowHalf && this.touchHalf) ?
// this.score : i;
this.score;
this.$emit('input', emitValue);
this.$emit('change', emitValue);
},
updateTouchHalf (i, e) {
let target = this.$refs[`star${i}`][0];
if (e.offsetX <= target.clientWidth / 2) {
this.touchHalf = true;
return;
}
this.touchHalf = false;
}
}
}
</script>
<style scoped>
.star-item {
display: inline-block;
position: relative;
}
.iconfont-main {
position: relative;
font-size: 24px;
margin-right: 8px;
}
.star-half {
position: absolute;
font-size: 24px;
left: 0;
top: 0;
width: 50%;
height: 100%;
overflow: hidden;
}
</style>