2👍
✅
The scope of this
is bound to Window instead of your Vue instance.
mounted: function() {
console.log(this); // Vue
setInternval(function() {
console.log(this); // Window
}, 1000);
setInterval(() => {
console.log(this); // Vue
}, 1000);
}
You had the right idea with your axios promises, .then(response => { .. })
in using the arrow function to preserve the scope of this
but you didn’t apply it to setInterval
.
If for some reason you really like the look of setInterval(function() { .. })
, or you need this
to be the Window object, you can create a variable and assign it to this
outside of the setInterval
function.
mounted: function() {
const vThis = this; // Vue
setInterval(function() {
axios({..})
.then(response => {
vThis.todos = response.data;
console.log(this); // Window
console.log(vThis); // Vue
})
.catch(error => {
});
}, 5000);
}
Source:stackexchange.com