Skip to content

Star Ratings

Daniel Zappala edited this page Feb 24, 2018 · 1 revision

Use this star rating library for Vue. Use the CDN method for loading the libary:

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

along with the suggestion for creating a Vue component:

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

Once this is done, you just need to create a star rating element in index.html and you need to create the appropriate backing code in script.js.

An example of an HTML element is:

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

This is using the shorthand for v-on, described at the bottom of the Template Syntax page.

You can now create a method called setRating:

methods: {
    setRating: function(rating){
      // Handle the rating
    }
  },

Since we are keeping a rating for each comic separately, you'll need an object to track this:

this.ratings[this.number].sum += rating;
this.ratings[this.number].number += 1;

To make this work, you need to check whether the object has a rating yet:

if (!(this.number in this.ratings))
   Vue.set(this.ratings,this.number,{sum:0,number:0});

Just like with the comments, we need to use Vue.set to setup a new property in an object so that Vue will track it.

You can now create a computed property that returns the average rating for the currently viewed comic.

Clone this wiki locally