Created
November 22, 2020 14:11
-
-
Save willwillems/9f001e603e4f79b724d7cf48115f6d82 to your computer and use it in GitHub Desktop.
Vue Component for 5 star rating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="product-rating" :class="{'product-rating--invalid': ratingIsNan}"> | |
<div class="product-rating__value-cutoff" :style="`width: ${cutoffWidth}%;`"> | |
<img class="product-rating__star" :class="{'product-rating__star--small': isSmall}" src="/icon/star.svg" /> | |
<img class="product-rating__star" :class="{'product-rating__star--small': isSmall}" src="/icon/star.svg" /> | |
<img class="product-rating__star" :class="{'product-rating__star--small': isSmall}" src="/icon/star.svg" /> | |
<img class="product-rating__star" :class="{'product-rating__star--small': isSmall}" src="/icon/star.svg" /> | |
<img class="product-rating__star" :class="{'product-rating__star--small': isSmall}" src="/icon/star.svg" /> | |
</div> | |
</div> | |
</template> | |
<script> | |
export default { | |
props: { | |
rating: { | |
type: Number, | |
default: 0, | |
validator: (n) => (n >= 0 && n <= 5) | |
}, | |
size: { | |
type: String, | |
default: 'md', | |
validator: (s) => (s === 'sm' || s === 'md') | |
} | |
}, | |
computed: { | |
ratingIsNan () { | |
return isNaN(this.rating) | |
}, | |
cutoffWidth () { | |
if (this.ratingIsNan) return 100 | |
return (this.rating/5) * 100 | |
}, | |
isSmall () { | |
return this.size === 'sm' | |
} | |
} | |
} | |
</script> | |
<style lang="postcss" scoped> | |
.product-rating { | |
@apply whitespace-no-wrap; | |
&__star { | |
@apply h-8 w-8 inline-block; | |
&--small { | |
@apply h-4 w-4; | |
} | |
} | |
&__value-cutoff { | |
@apply overflow-x-hidden; | |
} | |
&--invalid { | |
filter: grayscale(1); | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment