Vue equivalent of setTimeOut?

2019-03-10 15:38发布

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>

And the 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).

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.

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

My function is now:

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

9条回答
别忘想泡老子
2楼-- · 2019-03-10 16:15

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);
        }

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.

查看更多
三岁会撩人
3楼-- · 2019-03-10 16:16

after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }
查看更多
我想做一个坏孩纸
4楼-- · 2019-03-10 16:24

Add bind(this) to your setTimeout callback function

setTimeout(function () {
    this.basketAddSuccess = false
}.bind(this), 2000)
查看更多
登录 后发表回答