diff --git a/src/components/mdRatingBar/mdRatingBar.vue b/src/components/mdRatingBar/mdRatingBar.vue index da0a668..a643999 100644 --- a/src/components/mdRatingBar/mdRatingBar.vue +++ b/src/components/mdRatingBar/mdRatingBar.vue @@ -1,10 +1,15 @@ @@ -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; + } } };