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);
}
ES6 can bind 'this'
If you want to use the this keyword in your function, you need to write te setTimeout function in ES6
vuejs 2
first add this to methods
after that call this method on mounted
use
this.animationStop
, not use this.animationStop( )You can use Vue.nextTick
Kevin Muchwat above has the BEST answer, despite only 10 upvotes and not selected answer.
Let me explain WHY.
"Arrow Function" is ECMA6/ECMA2015. It's perfectly valid in compiled code or controlled client situations (cordova phone apps, Node.js), and it's nice and succinct. It will even probably pass your testing!
However, Microsoft in their infinite wisdom has decided that Internet Explorer WILL NOT EVER SUPPORT ECMA2015!
Their new Edge browser does, but that's not good enough for public facing websites.
Doing a standard function(){} and adding .bind(this) however is the ECMA5.1 (which IS fully supported) syntax for the exact same functionality.
This is also important in ajax/post .then/else calls. At the end of your .then(function){}) you need to bind(this) there as well so: .then(function(){this.flag = true}.bind(this))
I would have added this as a comment to Kevin's response, but for some silly reason it takes less points to post replies than to comment on replies
DO NOT MAKE THE SAME MISTAKE I MADE!
I code on a Mac, and used the 48 points upvoted comment which worked great! Until I got some calls on my scripts failing and I couldn't figure out why. I had to go back and update dozens of calls from arrow syntax to function(){}.bind(this) syntax.
Thankfully I found this thread again and got the right answer. Kevin, I am forever grateful.
As per the "Accepted answer", that has other potential issues dealing with additional libraries (had problems properly accessing/updating Vue properties/functions)