Vue equivalente a setTimeout?


Estoy haciendo un sistema de carrito de compras con Laravel y Vue. Cuando agrego un elemento a la cesta, muestro un mensaje de confirmación al alternar una variable Vue que está siendo observada por un v-if:

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

Y la JS:

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

(Y sí, voy a añadir esto en un entonces-captura en breve).

Esto funciona bien y aparece el mensaje. Sin embargo, me gustaría que el mensaje desapareciera de nuevo después de un cierto tiempo, digamos unos segundos. ¿Cómo puedo hacer esto con Vue? He intentado setTimeOut pero Vue no parece que me guste, diciendo que no está definido.

EDITAR: Estaba escribiendo mal setTimeout como un idiota. Sin embargo, todavía no funciona:

Mi función es ahora:

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

7 answers

Puedes probar este código:

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.

 29
Author: g.annunziata,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-18 07:59:29

Después de encontrar el mismo problema, terminé en este hilo. Por el bien de la generación futura: La respuesta actual más votada, intenta vincular "this" a una variable para evitar cambiar el contexto cuando invoca la función que se define en el setTimeout.

Un enfoque alternativo y más recomendado(usando Vue.JS 2.2 & ES6) es usar una función de flecha para enlazar el contexto al padre (Básicamente "addToBasket"'s "this"y el "setTimeout" ' s "this" todavía refiérase al mismo objeto):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }
 37
Author: Samuel Bergström,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-02 20:51:23

Agregue bind(this) a su función de devolución de llamada setTimeout

setTimeout(function () {
    this.basketAddSuccess = false
}.bind(this), 2000)
 9
Author: Kevin Muchwat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 12:29:00

Puede usar Vue.nextTick

addToBasket: function(){
                item = this.photo;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                Vue.nextTick(() =>{
                    this.basketAddSuccess = false;
                });
            }
 2
Author: Samundra Khatri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 14:56:20

Vuejs 2

Primero agregue esto a los métodos

methods:{
    sayHi: function () {
      var v = this;
      setTimeout(function () {
        v.message = "Hi Vue!";
    }, 3000);
   }

Después de eso llame a este método en montado

mounted () {
  this.sayHi()
}
 2
Author: mohamad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 08:39:20

Use this.animationStop, no use esto.animationStop ( )

animationRun(){
    this.sliderClass.anim = true;
    setTimeout(this.animationStop, 500);
},
 0
Author: Pax Exterminatus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-21 16:36:50

Si desea utilizar la palabra clave this en su función, debe escribir la función setTimeout en ES6

        setTimeout(() => {
            this.filters.max_budget_gt_eq = this.budgetHigherValue;
        }, 1000);
 0
Author: Wouter Schoofs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-10 13:51:57