VueJS axios 允许仅单击按钮一次,收到数据后允许第二次单击
P粉938936304
P粉938936304 2024-02-26 11:44:47
[Vue.js讨论组]

我正在 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粉938936304
P粉938936304

全部回复(2)
P粉752479467

this.allowed = false; 会一直被调用,直到 API 调用完成,这样您就可以在这段时间内发送更多垃圾邮件。 验证if(this.allowed)后立即将其设置为false

if (this.allowed) {
    this.allowed = false; // Then do the call
}
P粉477369269
    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;
       })
        ....
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号