DEV Community

Nenncy Finch
Nenncy Finch

Posted on • Edited on

Dynamic Star Rating With Vue.js

For one of my most recent ecommerce projects, I had to create a dynamic star rating of all the laptops. For that, I had to invest a few hours to research. So, I thought sharing the code of dynamic start rating in Vue.js may help you to add dynamic star rating in the least amount of time.

Travel through this code and get detailed information regarding the same!

For my project, I had to give the start rating to different laptops. I had to add different laptops in the database along with the star rating of those laptops.

I used MongoDB as the database and Node.js for the server. But, here in this article, I’m showing you how to create a dynamic star rating. So, I’m going to create a Javascript file that is going to have information about various laptops.

Laptops.js file:

const state = () => ({
    all: [
{
Id: 1,
Name: Hp laptops,
image: require('../assets/img/path_to_image.jpg'),
star1: 'fas fa-star',
            star2: 'fas fa-star',
            star3: 'fas fa-star',
            star4: 'fas fa-star',
            star5: 'fas fa-star-half-alt',
}
{
Id: 2,
Name: Dell Laptops,
image: require('../assets/img/path_to_image.jpg'),
star1: 'fas fa-star',
            star2: 'fas fa-star',
            star3: 'fas fa-star',
            star4: 'fas fa-star',
            star5: ' ',
}
    ]
});

export default {
    state
};

Enter fullscreen mode Exit fullscreen mode

Explanation of the code:

Here, in my code, I announced stars as independent variables. Along with that, there are two important classes for full stars and a half star. Here, ‘fas fa-star’ class name is used for the full star, and ‘fas fa-star-half-alt' is used to show the half star of the laptops. And incase, you want to give four stars to any laptop or product then leave the star5 blank. So simple, right?

Now, show the star ratings to the laptops in your Vue.js Code:

<div class="rating">
                    <i :class="laptop.star1"></i>
                    <i :class=" laptop.star2"></i>
                    <i :class=" laptop.star3"></i>
                    <i :class=" laptop.star4"></i>
                    <i :class=" laptop.star5"></i>
                </div>

Enter fullscreen mode Exit fullscreen mode

In the above code, I bound the class CSS property to the star values I have in my database.

You may find the technique not the best technique to show a star rating but I used this in my laptop project. If you have used any other technique in the past then do share it with me, I will be glad to read your idea. Check out my star rating of the laptops. Apart from that, if you have any confusion in the code then do not hesitate to drop a comment below in the comment box.

Top comments (0)