nscode
nscode

Reputation: 157

How to limit a like button spamming in Vue/Laravel

The issue is that if you consistently press fast several times, the vote number go crazy on the frontend (the backend is fine bcause it's just attach(voteup) and detach(unvote) operation).

A user can upvote and can un-vote if previously voted up.

the button in blade:

<vote 
    :votes="{{ $question->votes()->count() }}"
    :question="{{ $question->id }}"
    :voted="{{ $question->currentUserVoted() ? 'true' : 'false' }}"
></vote>

The vue component:

<template>
    <span>
        <a href="#" v-if="isVoted" @click.prevent="voteDown(question)">
            <i class="fas fa-caret-up fa-3x text-primary vote-effect vote-up-effect"></i>
        </a>
        <a href="#" v-else @click.prevent="voteUp(question)">
            <i class="fas fa-caret-up fa-3x vote-gray vote-effect"></i>
        </a>
        <span class="vote-count-post "><strong>{{ this.votes }}</strong></span>
    </span>
</template>

<script>
    export default {
        props: ['question', 'voted', 'votes'],

        data: function() {
            return {
                isVoted: '',
            }
        },

        mounted() {
            this.isVoted = this.isVote ? true : false;
        },

        computed: {
            isVote() {
                return this.voted;
            },
        },

        methods: {
            voteUp(question) {
                axios.post('/voteup/'+question)
                    .then(response => this.isVoted = true, this.votes = this.votes + 1)
                    .catch(response => console.log(response.data));
            },

            voteDown(question) {
                axios.post('/votedown/'+question)
                    .then(response => this.isVoted = false, this.votes = this.votes - 1)
                    .catch(response => console.log(response.data));
            }
        }
    }
</script>

Upvotes: 1

Views: 330

Answers (1)

BTL
BTL

Reputation: 4656

You can use @click.once

<template>
    <span>
        <a href="#" v-if="isVoted" @click.once="voteDown(question)">
            <i class="fas fa-caret-up fa-3x text-primary vote-effect vote-up-effect"></i>
        </a>
        <a href="#" v-else @click.once="voteUp(question)">
            <i class="fas fa-caret-up fa-3x vote-gray vote-effect"></i>
        </a>
        <span class="vote-count-post "><strong>{{ this.votes }}</strong></span>
    </span>
</template>

Upvotes: 1

Related Questions