搜尋

首頁  >  問答  >  主體

VueJS axios 允許僅單擊按鈕一次,收到資料後允許第二次單擊

我正在 Laravel/VueJS 上做喜歡/不喜歡系統。

我的系統可以運行,但我想避免垃圾郵件發送者。

按讚按鈕:

<a v-on:click="like(10, $event)">
    <i class="fas fa-heart"></i>
</a>

10是post id,它是在laravel Blade中產生的...

這是我試圖避免垃圾郵件發送者的方法:

const app = new Vue({
el: '#app',
data() {
    return {
        allowed: true,
    };
},
methods: {
    like: function (id, event) {
        if (this.allowed) {
            axios.post('/posts/' + id + '/like', {  
                post_id: id,
            })
            .then((response) => {
                this.allowed = false; //Set allowed to false, to avoid spammers.

                ..... code which changes fa-heart, changes class names, texts etc ....

                // send notification to user
                Vue.toasted.show('Bla bla bla successfuly liked post', {
                    duration: 2000,
                    onComplete: (function () {
                        this.allowed = true //After notification ended, user gets permission to like/dislike again.
                    })
                });

但是這裡缺少一些東西,或者我做錯了什麼。當我非常非常快地單擊類似圖標並檢查請求時,axios 發送 3-4-5 個請求(取決於您單擊的速度)

只有在 3-5 個請求之後 data.allowed 才會變成 false。為什麼?我想要:

  1. 允許= true;
  2. 用戶點擊 -> allowed = false; >第二次點擊「您不能再點擊,因為先前的通知尚未結束」;
  3. 上一個通知結束 -> allowed = true;
  4. ...循環

P粉938936304P粉938936304274 天前481

全部回覆(2)我來回復

  • P粉752479467

    P粉7524794672024-02-27 10:11:57

    this.allowed = false; 會一直被調用,直到 API 呼叫完成,這樣您就可以在這段時間內發送更多垃圾郵件。 驗證if(this.allowed)後立即將其設定為false

    if (this.allowed) {
        this.allowed = false; // Then do the call
    }

    回覆
    0
  • P粉477369269

    P粉4773692692024-02-27 09:15:48

        like: function (id, event) {
            // first, check if the `like` can be sent to server
            if (!this.allowed) return;
            // remember that we are sending request, not allowed to `like` again
            this.allowed = false;
    
            var self = this;  // you need this to remember real this
            axios.post('/posts/' + id + '/like', {  
                post_id: id,
            }).then((response) => {
                ..... code ....
    
                // send notification to user
                Vue.toasted.show('Bla bla bla successfuly liked post', {
                    duration: 2000,
                    onComplete: function () {
                        //After notification ended, user gets permission to like/dislike again.
                        self.allowed = true;
                    }
                );
           }).catch(function() {
                // maybe you also need this catch, in case network error occurs
                self.allowed = true;
           })
            ....
    

    回覆
    0
  • 取消回覆