[rating-bar] implement user input

This commit is contained in:
Laercio Santana 2017-03-18 05:38:10 +00:00
parent 4b07c3c5ef
commit b76463634b

View file

@ -1,10 +1,15 @@
<template>
<div class="md-rating-bar" :class="[themeClass]" :disabled="disabled">
<div class="back-stars" :disabled="disabled">
<md-icon v-for="i in numStars">star</md-icon>
<md-icon v-for="i in numStars" :key="i"
@mouseover.native="hoverStars"
@click.native="clickStars">star</md-icon>
</div>
<div class="front-stars" :style="frontStarsStyle">
<md-icon v-for="i in numStars" class="md-accent">star</md-icon>
<md-icon v-for="i in numStars" class="md-accent"
@mouseover.native="hoverStars"
@click.native="clickStars"
@mouseout.native="onMouseOut">star</md-icon>
</div>
</div>
</template>
@ -22,13 +27,22 @@
type: Number,
default: 5
},
rating: {
disabled: Boolean,
value: {
type: Number,
validator: (value) => {
return value >= 0 && value <= 1;
},
default: 0
},
disabled: Boolean
}
},
mixins: [theme],
data: () => ({
rating: NaN
}),
mounted: function() {
this.rating = this.value;
},
computed: {
frontStarsStyle() {
return {
@ -36,6 +50,45 @@
'margin-left': -iconSize * this.numStars + 'px'
};
}
},
watch: {
value(val) {
this.rating = this.value;
}
},
methods: {
hoverStars(evt) {
if (!this.disabled) {
var selected = this.getIconIndex(evt.target);
this.rating = selected / this.numStars;
}
},
clickStars(evt) {
if (!this.disabled) {
var selected = this.getIconIndex(evt.target);
this.$emit('input', selected / this.numStars);
}
},
getIconIndex(iconSelected) {//icon is a dom element
let ratingIcons = this.$el.querySelectorAll('.back-stars > .md-icon, .front-stars > .md-icon');
let selected = -1;
ratingIcons = Array.prototype.slice.call(ratingIcons);
ratingIcons.some((icon, i) => {//find index
if (icon === iconSelected) {
selected = (i + 1) % this.numStars;
selected = !selected ? this.numStars : selected;
return true;
}
});
return selected;
},
onMouseOut() {
this.rating = this.value;
}
}
};
</script>