When working with vuejs and JS scopes, passing a value to a style property inside data can be tricky. The issue arises when trying to access this.data.property:
Vue.component ('loader-component', {
template: '#loader-template',
mounted: function() {
this.animationTest();
},
data: function() {
return {
svg: true,
timer: 0,
// styles
position: {
marginLeft: '',
marginTop: '',
float: 'left'
}
};
},
methods: {
animation: function() {
let timer = 0,
itemWidth = 60,
domWidth = document.getElementById('awesome-body').clientWidth,
domHeight = document.getElementById('awesome-body').clientHeight,
marginL = -2 * itemWidth,
marginT = Math.floor((Math.random() * domHeight) + 1);
this.position.marginTop = marginT;
setInterval(function() {
marginL = marginL + timer * 5;
timer++;
// console.log(marginL);
this.position.marginLeft = marginL;
}, 1000); // time interval in milliseconds
}
} // methods finishes
});
This code snippet will result in the following error message:
Cannot set property 'marginLeft' of undefined.
Is there a specific syntax to directly access data.marginTop from the setInterval function?
Thank you!