Skip to content

Instantly share code, notes, and snippets.

@willwillems
Created November 22, 2020 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willwillems/9f001e603e4f79b724d7cf48115f6d82 to your computer and use it in GitHub Desktop.
Save willwillems/9f001e603e4f79b724d7cf48115f6d82 to your computer and use it in GitHub Desktop.
Vue Component for 5 star rating
<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