Build a voting system like Reddit one

I’m one of Reddit visitor from time to time. I was impressed on their comment system, actually I don’t know the technologies they are used for building that comment system who based on up and down vote.
So I decided to play around and try to build something similar to that in front-end side, so I tried that using VueJs.. and I will share with you who you can do the same. And I will gives you the demo at the end of this blog post.
I will use bootstrap for arrows to simplify the work.
Let’s set up our simple body code.

    <div id="app">
     <i class="glyphicon glyphicon-chevron-up"></i>
     <i class="glyphicon glyphicon-chevron-down"></i>
     <span>This is an simple title</span>
    </div>

Now I will go to create two function (upVote) and (downVote) who will be responsible to handle the the the functionalities and store them in vue Computed Properties (allVotes), that will show us the number of votes.

    new Vue({
        el: "#app",
        data() {
            return {
            up: false,
            down: false,
            votes: 10
            };
        },
        computed: {
            allVotes(){
            if(this.up){
                return this.votes +1
            }
            else if (this.down){
                return this.votes -1
            }
            else {
                return this.votes;
            }
            }
            },
        methods: {
            upVote(){
            this.up = !this.up;
            this.down = false;
            },
            downVote(){
            this.down = !this.down;
            this.up = false;
            }
        },
    })

Now we will update our code base by adding @clicks event listener to our two functions

    <div id="app">
    <i @click="upVote" class="glyphicon glyphicon-chevron-up"></i>
     <span>{{ allVotes }}</span>
    <i @click="downVote" class="glyphicon glyphicon-chevron-down"></i>
    <span>This is an simple title</span>
    </div>

To limit the up down for single user i will add css class to handle that with css

        .disabled {
            color: orange;
        }

So our HTML code will be like this:

    <div id="app">
	<i @click="upVote" class="glyphicon glyphicon-chevron-up" :class="{disabled: up}"></i>
     <span>{{ allVotes }}</span>
     <i @click="downVote" class="glyphicon glyphicon-chevron-down" :class="{disabled: down}"></i>
    <span>This is an simple title</span>
		
    </div>

LIVE DEMO

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *