Giter VIP home page Giter VIP logo

vue-star-rating's Introduction

Star Rating Component for Vue 2.x / 3.x

Build Status npm

A simple, highly customisable star rating component for Vue 2.x. / 3.x

Need more than stars? Check out vue-rate-it with hundreds of different raters built in!

Screenshot

star-rating.png

See it in action:

Features:

  • SVG stars - scale without loss of quality.
  • Customisable rating increments.
  • Customisable colors.
  • Customisable number of stars.
  • Create read-only stars.

Usage

Install Via NPM

Install via npm:

Vue 2.x Install

npm install vue-star-rating

Vue 3.x Install

If you're using Vue 3 you will currently need to install the next version of vue-star-rating

npm install vue-star-rating@next


Once installed import in to your component:

import StarRating from 'vue-star-rating'

Then register vue-star-rating using the components option:

components: {
  StarRating
}

You can then use the following markup in your project:

<star-rating />


Via CDN

You may also include vue-star-rating directly in to your webpage via Unpkg. Simply add the following script tag:

Vue 2.x

<script src="https://unpkg.com/vue-star-rating/dist/VueStarRating.umd.min.js"></script>`

You will need to register the component by doing:

Vue.component('star-rating', VueStarRating.default);

Vue 3.x

<script src="https://unpkg.com/vue-star-rating@next/dist/VueStarRating.umd.min.js"></script>
const app = Vue.createApp({ 
  // Your component code
 })
app.component('star-rating', VueStarRating.default)
app.mount('#app')

Getting Started

To get started with vue-star-rating you will want to sync the rating values between the component and parent, you can then take a look at the props and custom events section of the docs to customise your star-rating component.

Syncing Rating Values with V-Model

vue-star-rating supports v-model, which is the simplest way to keep your ratings in sync:

Vue 2.2+

<star-rating v-model="rating"></star-rating>

Vue 3.x

v-model works on the rating prop, so if you're using Vue 3 you will need to do:

<star-rating v-model:rating="rating"></star-rating>

Docs

Props

The following props can be passed to the component:

General Props

These props provide general functionailty to the star rating component

Prop Description Type Default
increment The rating increment, for example pass 0.5 for half stars or 0.01 for fluid stars. Expects a number between 0.01 - 1. Number 1
rating The initial rating, this will automatically round to the closest increment, so for the most accurate rating pass 0.01 as increment or set the round-start-rating prop to false Number 0
max-rating The maximum rating, this lets vue-star-rating know how many stars to display Number 5
star-points The points defining a custom star shape.
If no points are passed the default star shape is used.
Array []
read-only When set to true, the rating cannot be edited. Use in conjuction with increment to define rounding precision. Boolean false
show-rating Whether or not to show the rating next to the stars Boolean true
fixed-points Specify a fixed number of digits after the decimal point. Number null
rtl Pass true to display star rating using rtl (right-to-left) Boolean false
round-start-rating Pass false if you don't want the start rating value to round to the closest increment. The user will still only be able to select based on the given increment. Boolean true
clearable When set to true a second click on the same rating clears the rating Boolean false
active-on-click When set to true only apply active colors when the user clicks the star, rather than on mouseover. Boolean false

Style Props

These props are used to style the star rating component

Prop Description Type Default
star-size The size of each star, this gets passed to the SVG width attribute, so larger numbers are larger stars Number 50
inactive-color The color of the non-highlighted portion of a star. String #d8d8d8
active-color The color of the highlighted portion of a star. Pass an array of colors to color each star individually String | Array #ffd055
border-color Sets the colour of the border for each star String #999
active-border-color The border color of a highlighted star. Pass an array of colors to color each star's border individually String | Array null
border-width Sets the width of the border for each star Number 0
animate Set to true for an animation to be applied on mouseover Boolean false
padding Pads the right of each star so distance between stars can be altered Number 0
rounded-corners Whether or not to round the star's corners Boolean false
inline Sets the star rating to display inline Boolean false
glow Adds a subtle glow around each active star, this should be a number to spread the glow Number 0
glow-color Sets the color for the glow String #fff
text-class A css class name to style the rating text for a specific star rating component String ''

Important: Vue requires you to pass numbers and boolean values using v-bind, any props that require a number or bool should use v-bind: or the colon (:) shorthand.

Props Example

<star-rating v-bind:increment="0.5"
             v-bind:max-rating="3"
             inactive-color="#000"
             active-color="#f00"
             v-bind:star-size="90">
</star-rating>

Passing an Array of Colors

The active-color and active-border-color props also accept an array of colors. The colors in the array will be applied to the stars in order, so index 0 will be the color of the first star, index 1 will be the second and so on. Any array you pass will be padded if the number of elements in the array is less than the number of stars. This means that the following code will color the first star red and ALL remaining stars black.

<star-rating :active-color="['red','black']">
</star-rating>

Custom Events

vue-star-rating fires the following custom events, simply use v-on: or the @ shortand to capture the event.

Vue 2.x Events

Event Description Return Value
rating-selected Returns the rating the user selects via the click event rating
current-rating Returns the rating that the users mouse is currently over rating

Vue 2.x Example

<star-rating @rating-selected ="setRating"></star-rating>

Then in your view model:

new Vue({
  el: '#app',
  methods: {
    setRating: function(rating){
      this.rating= rating;
    }
  },
  data: {
    rating: 0
  }
});

Vue 3.x Events

Some changes have been made to event names in Vue 3

Event Description Return Value
update:rating Returns the rating the user selects via the click event rating
hover:rating Returns the rating that the users mouse is currently over rating

Vue 3.x Example

<star-rating @update:rating ="setRating"></star-rating>

Then in your view model:

const app = Vue.createApp({
  methods: {
    setRating(rating){
      this.rating= rating;
    }
  },
  data: {
    rating: 0
  }
})
app.component('star-rating', VueStarRating.default)
app.mount('#app')

Screen Reader Support

vue-star-rating has built in support for screen readers. By default this message will read "Rated {{rating}} out of {{maxRating}} stars", you can change this by using the screen-reader scoped slot:

<star-rating>
    <template v-slot:screen-reader="slotProps">
        This product has been rated {{slotProps.rating}} out of {{slotProps.stars}} stars
    </template>
</star-rating>

IE9 Support

vue-star-rating supports IE 9+; make sure you place the following in the head of your webpage to ensure that IE is in standards mode:

<meta http-equiv="X-UA-Compatible" content="IE=Edge">


Open-source should always be 100% FREE! but, if you're feeling generous, feel free to:

Buy Me A Coffee

vue-star-rating's People

Contributors

craiggoescoding avatar craigh411 avatar dominikserafin avatar eiji03aero avatar nabebin avatar sparohawk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-star-rating's Issues

Padding not working

It's me or the prop padding is not working, even if you add just 1 for padding the space between is super large.... Did I miss anything?

screen shot 2017-11-21 at 2 29 52 pm

<star-rating :increment="0.5" :max-rating="5" :star-size="15" :show-rating="false" :read-only="true" border-color="#A1AAB3" border-width="1" inactive-color="#FFF" active-color="#E6B235" v-model="rating" padding="1"> </star-rating>

Stars look pixelated with high contrast

This can be seen on the JSFiddle example linked in the readme for the red stars on non-retina displays:
sc.

It looks fine on a retina display though.

Tested and reproducible on macOS with most recent chrome, firefox and safari.

I suppose it's a problem with the svgs, but I'm not very familiar with the format or svg rendering.

Reseting rating

Hello,

Any idea about how to reset the rating to 0 and empty the gauge ?

I did many tries but nothing really happend correctly

Thanks a lot !

Responsive

Hi,
Nice component
But I did app for desktop and mobile.
I can not use this component on mobile. It is not responsive

Issue?

Just after import I get this Error:

ERROR in ./~/vue-star-rating/src/star-rating.vue Module parse failed: .../node_modules/vue-star-rating/src/star-rating.vue Unexpected token (1:0) You may need an appropriate loader to handle this file type. | <template> | <div> | <div @mouseleave="resetRating" id="stars">

...imported in a project with a lot of other dependencies, all installed with npm, all included in package.json (using webpack and Vue 2.1.8 )
Can't see any error, do you have a hint?

Screen Reader support

Thanks for a very useful component! I am making use of this project to provide star ratings on a project and we're aiming for a great experience for screen reader users. Currently, when a screen reader hits the star ratings it just skips it.

My quick solution on my app was to do this:

<div class="ratings">
    <span class="sr-only">This clinic is rated {{ rating }} stars out of five.</span>
    <star-rating v-model="rating"
                       :show-rating="false"
                       active-color="#d6612d"
                       :star-size="20"
      ></star-rating>
</div>

By adding that span, the screen reader gets a solid sensible experience, perhaps it would be a good idea to have something like it by default that is visually hidden but translates the component contents to something that verbally makes sense?

need SSR usage example

I'm rendering my pages on server side and I found a problem that only occurs on first page render.
When I'm trying to access a page with StarRating I get the following error:

Vue warn]: Error in beforeCreate hook: "ReferenceError: document is not defined" found in
---> <StarRating>
          <Component> at ../src/components/Component.vue
             <App> at ../src/App.vue
               <Root>

Call stack gives much more info

ReferenceError: document is not defined
at o (../node_modules/vue-star-rating/dist/webpack:/~/vue-style-loader/lib/addStylesClient.js:116:1)
at r (../node_modules/vue-star-rating/dist/webpack:/~/vue-style-loader/lib/addStylesClient.js:100:1)
at t.exports (../node_modules/vue-star-rating/dist/webpack:/~/vue-style-loader/lib/addStylesClient.js:54:1)
at Object.e (../node_modules/vue-star-rating/dist/webpack:/src/star-rating.vue?3ff3:8:1)
at e (../node_modules/vue-star-rating/dist/webpack:/webpack/bootstrap 1d3fc18262fd606c10d8:19:1)
at VueComponent.r (../node_modules/vue-star-rating/dist/webpack:/src/star-rating.vue:2:1)

Due to vue-style-loader page you need to build server side files with target: 'node' to prevent this from happening.
After a short research I solved this problem by changing import to

import StarRating from 'vue-star-rating/src'

Maybe it's worth adding in README.md to prevent inexperienced users like me from this error

Star rating not working in Safari

I am facing an issue with Star Rating in Safari (Version 12.0.2 (14606.3.4)).

The star rating is being set in my v-model, but the active stars are not being highlighted.

Vue version: 2.6.7

Vue Star Rating version: 1.6.1

Here is a screenshot:

image

How to make some star-rating elements disabled

Hello,
In vuejs 2.6 app I use
"vue-star-rating": "^1.6.1"
and having listing of star-rating elements I need to make some of them disabled for clicking.
I found some hints on the site, like

                    <star-rating
                        v-model="nextHostelReview.stars_rating_type_id"
                        isIndicatorActive="true"
                        :config="config"
                        :max-rating="nextHostelReview.stars_rating_type_id"
                        :min-rating="nextHostelReview.stars_rating_type_id"
                        :rating="nextHostelReview.stars_rating_type_id"
                        :star-size="20"
                    ></star-rating>

but I failed.
I need something like :

                    <star-rating
                    ...
                        disabled="true"
                        readonly="true"
                    ></star-rating>


```Are there ?

Thanks!

[Vue warn]: Failed to mount component: template or render function not defined.

I keep getting the error described in the title when trying to load the component.

// HTML
<div class="container" id="main">        
    <star-rating></star-rating>
</div>

// Javascript
var StarRating = require('vue-star-rating');
var Vue = require('vue');
Vue.component('star-rating', StarRating);

new Vue({
    el: "#main",
    data: {
         
    },
    methods: {
        
    },
    mounted: function() {
        window.Laravel.debug && console.log('Survey Vue Mounted!');
    }
});

Prop to hide inactive stars

Hi and thanks for this great lib !

Would it be possible to add a prop, let's say inactive-show, which would remove the inactive stars if true ?
I'm asking that because I'm mostly using this lib to display hotel rating, which is a fixed value of stars.
Right now my workaround is inactive-color="white" if my background is white, but this is kind of hacky !

If you don't have the time for, I'm up for a PR !

Thanks for your time

Validation

Could we have validation for when used in a form?

Remove rating?

Nice plugin but Is there a way to remove the rating?
Example : I rate 5 but finally I want to delete my rating, I should be able to do it by clicking on the left of the 1st star

Stars in Dark background gets something like light border

Hello,

I have used your star component it is awesome. However, I am getting UI issue when dark background is used.

Please check this image:
dark-bg

I also get white stroke in yellow stars, if size is small. Try changing code for glowing stars in your jsfiddle example to below code.

  <h2>Glowing Stars</h2>
  <div style="background:#000;padding-bottom:10px;">

    <star-rating :star-size="20"></star-rating>
  </div>

Result shade of light grey or white:
glow

I am also getting same in my project which is live. You can check how it looks in below image.
dist

However, this might looks tiny issue but if we use dark theme in our app as eveybody loves now a days it brings this issue.

Awesome Component BTW.
Waiting for your response.

~ Regards

enhancement: need config parameter min-rating

As of now, even with a stepping of 1, it is possible to give a 0-stars rating. Most existing implementations require that the user can vote only between 1 and 5 stars.

It should be possible to configure a minimum rating value. Of course this can be done using the rating-selected event handler (like not applying the vote if the value is less than 1 or whatever the user wants as a minimum), but since this will be a standard requirement this should probably be implemented as a config option min-rating.

direction star rtl

this is my rate
rating

this is my cod
<star-rating :rating="3.37" :increment="0.01" :read-only="true" :star-size="20"></star-rating>
how solve,
thank for help...

Cancelling Rating by Clicking on first Start

Hi Craig,

Thanks for Vue Star Rating -- great component!

Is it possible to cancel a rating by clicking the first star? Currently when I click the first star it says on.

Thank you,

Ronnie Serr

Displaying rating text

How can I display the rating text in a label instead of having it right beside the stars.

I want to get the value of the selected rating and display it in a label. is there a way to achieve this?

v-model doesn't work

Hello,

I have an issue with the v-model to reset the rating,

When rating is selected, it should run the function Reseting to change the var rating to 0,

If I make a test to run the function from a button, it works but not after rating,

Any idea ?

Thanks!

<template>
  <div class="page-wrapper">
    <img alt="logo-bento" class="logo" src="@/assets/img/bento-starter.png" />
    <star-rating v-model="rating"  @rating-selected="reseting" ></star-rating>
    <h4> You have voted {{ MyVote }}/5 </h4>
    <Catloader ref="foo"></Catloader>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import Catloader from '@/components/CatLoader'
import StarRating from 'vue-star-rating'

export default {
  components: {
    Catloader,
    StarRating
  },
  data()  {
    return {
      rating: 0,
      MyVote: 0
    }
  },
  head() {
    return {
      title: {
        inner: 'Home'
      },
      meta: [
        {
          name: 'description',
          content: `${this.appTitle} home page`,
          id: 'desc'
        }
      ]
    }
  },
  computed: mapState('app', ['appTitle']),
  methods: {
    reseting() {
      console.log(this.rating)
      this.MyVote = this.rating
      this.rating = 0
      return this.rating
    }
  }
}
</script>

Alternative to stars?

Could I replace the stars with some box with the corresponding number ?
If yes, what is the best way to achieve that? Thanks!

Numbers Within Stars

Hello!
Thanks for Vue Star Rating!

I need to enumerate the stars by displaying a number inside them (see image).

image

Would it be possible to implement a boolean property to let me know if I want to show these numbers or not?
Or maybe a property by which I can send an object (with the same number of elements as max-rating) so that I can show in its respective star?

Thank you in advance!

Border-color active and inactive

Is it possible to style the border-color depending on whether it is active or not?
Like inactive-color -> inactive-border-color ?

show-rating=false does not work

This is what i have:

<rating class="rating-stars"
             rating="2"
             increment="0.25"
             read-only="true"
             active-color="#dc2234"
             inactive-color="#676767"
             star-size="20"
             show-rating="false"/>

This is what i get:

image

So the show-rating="false" does not work

It shows only one star

I am trying to show 5 stars with half increment. All works fine but all I can see only 1 star.

Please help thank you.

round-start-rating is respected after first hover

This is how I set the initial rating.

    <star-rating ref="widget"
        v-model="rating"
        @rating-selected="setRating"
        :round-start-rating="false">
     </star-rating>

        beforeMount: function() {
            this.ratingIdentifier = this.getRatingIdentifier();
            this.readOnly = undefined !== localStorage[this.ratingIdentifier];
            this.maxRating = window.vueData.rating.maxRating;
            this.getRating();
        },
        methods: {
            getRating: function() {
                  // 3.5 is actually from an async callback
                  this.rating = 3.5;
            }
        }

Expected behavior:

  • initial rating shows 3 1/2 stars.
  • rating should be possible in increments of 1, no half stars

Actual behavior:

  • initial rating shows as 4 stars.
  • rating is possible in increments of 1, no half stars
  • after hovering (not selecting anything) the widget shows a rating of 3 1/2 stars.

Am I setting the rating at a wrong time?

I'm using version 1.6

iOS devices require "double tap" to select rating

I seem to be having an issue where the rating only works on iOS if you double-tap the star. I suspect this has to do with using mouseevents, but I'm not sure.

The stars appear to be selected (they turn yellow) but the v-model is only updated with a second tap on the same star.

Star inactive opacity

I want to be able to make my stars transparent.

I can do this in Chrome by setting the inactive-color to a color that has opacity, e.g. #000000, or rgba(0, 0, 0, 0).

This unfortunately doesn't work in Safari, because SVG grandients ignore color opacity in the stop elements inside the linear-gradient element. To get it to work you need to set an attribute stop-opacity on the stop element inside the gradient. To see what I mean, you can open this CodePen in Chrome and Safari and see the difference: https://codepen.io/AmeliaBR/pen/jrBOBv/

So I'd like to add an attribute on this star rating component called inactive-opacity or something like that, which would then set the opacity for the inactive gradient stops.

If you'd agree that it would be a useful feature for the component, I'll see if I can add it and make a pull request.

TypeScript Support

Any plans to add TypeScript support? Or has anyone using this library managed to get this working with TypeScript?

config global how it work?

hi boy
i want add global config so add this

Vue.component('star-rating', StarRating);
Vue.use('star-rating',StarRating, {
  'rounded-corners':true,
  'borderColor':'red'
});

or

import StarRating from 'vue-star-rating'
Vue.component('star-rating', StarRating, {
    'rounded-corners':true,
    'borderColor':'red'
  });

but don't work how add config global?
Tnx for help ...

Need dynamic stepping or distinction between display increment and usage increment

Most of today's real life implementations of rating stars are used for double purpose:

  1. Display the current average rating of an item;
  2. Interact with this display to give your own rating.

This leads to a big problem:

The average rating obviously will rarely be 3 or 4, but rather a floating point number like 3.71 or 4.29. This needs to be displayed properly. For this to display properly it is currently necessary to set an increment of 0.01.

The user that wants to use the stars to give their own rating usually is supposed to choose between giving either 1, 2, 3, 4 or 5 stars. (this explicitly also means you cannot rate lower than 1). This currently requires to set increment to 1.

This could be solved by either allowing for a dynamic re-evaluation in case the increment value changes, or, even better, differentiating between a config parameter which serves for display purposes only, and another for entry purposes.

Small-sized stars differ in size

Size on whole stars are too large when star-size is ~12

<star-rating :star-size="12"
                read-only
                :show-rating="false"
                :rating="rating"
                :value="rating"
                @input="onRatingInput"
                :increment="0.5" />

screenshot 2018-12-04 at 21 54 23

Glow is always on

it seems to me that the glow is always on.

Given the follow set up

          <star-rating
            v-model="rating"
            v-if="rating !== null"
            :read-only="true"
            :increment="0.1"
            active-color="#d6612d"
           text-class="rating__text"
            :star-size="20"
          >

I get the following result:

image

Explicitly setting :glow="0" doesn't change the outcome which is to be expected as the default is 0 anyway.

Setting the glow color explicitly shows that it is in fact the glow showing through despite 'glow' being set to o0

image

Unable to resize

screen shot 2017-05-16 at 2 39 06 pm

Here's my markup:
<star-rating :rating="3.8" :star-size="30" :read-only="true" :increment="0.01"></star-rating>

[suggestion] v-model implementation?

Thanks for your great library!
I am really happy to use it.

This is not a problem but just a suggestion.
For reactive data binding, I wrote the following code:

<template>
  <star-rating  
      :rating="rating"
      @rating-selected="value => {rating = value}">
  </star-rating>
</template>

<script>
  new Vue({
    data() {
      return { rating: 3 }
    }
  })
</script>

How about to set reactive v-model attribution?
The code should be like this, simply:

<template>
  <star-rating v-model="rating"></star-rating>
</template>

I think we can do it by adding value prop to star-rating component and emit input event with the argument this.selectedRating.

If you accept this feature, I will try to code.

Thanks!

Using the CDN

Hello
How you add js file in css link tag?

Best regards
Christoph

v1.4.0 introduced breaking changes

Thanks for the continued support and improvements for this useful vue component!

I noticed that v1.4.0 introduced a breaking change for our usage of this component: the main entry in package.json was changed from src/star-rating.vue to dist/star-rating.min.js. Our usage of this component is a direct import of the src/star-rating.vue single file component file, this change broke our build and the component using this component failed to render the <star-rating> component.

I think this should be considered a breaking change. Along with the CSS class name changes, I think bumping the major version would be more appropriate? i.e. v2.0.0 instead of v1.4.0.

For now I have to change the semver notation of this package from ^1.3.2 to ~1.3.2 to lock it to the 1.3.x version, so that whenever we shrinkwrap again we don't get bumped to v1.4.0.

Cheers.

Is there an option to center the whole stars?

The stars are aligned to start from left to right and that made it unfit in a layout where I have all text and images aligned center. Was able to add:

.vue-star-rating{
  justify-content: center;
}

to center it but I want to know if there's an option for this or if it could be added. I can work on a PR

All stars black in Safari

Firefox and Chrome correctly show the default colours, but Safari is just rendering all the stars as black

number of reviews

can we add how many review has been given like i shared in screenshot
rating

just beside the rating...

if its possible can someone please help me with that??

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.