Vue相当于setTimeOut? [英] Vue equivalent of setTimeOut?

查看:100
本文介绍了Vue相当于setTimeOut?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Laravel和Vue制作购物车系统。当我将项目添加到购物篮时,我通过切换由v-if监视的Vue变量来显示确认消息:

I'm making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

<div class="alert alert-success" v-if="basketAddSuccess" transition="expand">Added to the basket</div>

和JS:

addToBasket: function(){
                item = this.product;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
            }

(是的,我会在短期内加入这个) 。

(And yes, I will be adding this in a then-catch shortly).

此工作正常,并显示消息。但是,我希望这段消息在一段时间后再次消失,比如几秒钟。我怎么能用Vue做到这一点?我已经尝试了 setTimeOut 但是Vue似乎不喜欢它,说这是未定义的。

This works fine and the message appears. However, I'd like the message to disappear again after a certain time, say a few seconds. How can I do this with Vue? I've tried setTimeOut but Vue doesn't seem to like it, saying it's undefined.

编辑:我拼错了 setTimeout 就像一个白痴。但是,它仍然不起作用:

I was misspelling setTimeout like an idiot. However, it still doesn't work:

我的功能现在是:

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){
                    this.basketAddSuccess = false;
                }, 2000);
            }


推荐答案

您可以尝试以下代码:

You can try this code:

addToBasket: function(){
            item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            var self = this;
            setTimeout(function(){
                self.basketAddSuccess = false;
            }, 2000);
        }

迷你解释:由setTimeout调用的内部函数 this 不是VueJs对象(是setTimeout全局对象),但 self ,也是在2秒后调用,仍然是VueJs对象。

Mini-explain: inside function called by setTimeout this is NOT VueJs object (is setTimeout global object), but self, also called after 2 seconds, is still VueJs Object.

编辑1:带箭头功能的示例

addToBasket () {
    var item = this.photo;
    this.$http.post('/api/buy/addToBasket', item);
    this.basketAddSuccess = true;
    // now 'this' is referencing the Vue object and not 'setTimeout' scope
    setTimeout(() => this.basketAddSuccess=false, 2000);
}

这篇关于Vue相当于setTimeOut?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆