I'm having some problems using this
in VUE single file components (or any component for that matter).
This is probably not VUE specific issue (more javascript), but I've ran into it, while creating a VUE application.
In VUEJS this
keyword is used inside single vue component to refer to the component itself. But if scope is changed (e.g. forEach loop), this
no longer refers to the component but (as in example), this
refers to the array being iterated.
One solution to this is to save this
value first (e.g. var self = this;
).
Example (not working):
<script>
export default {
data() {
return {
someProp: "stringValue",
myArray: [
{ "key": "key1", "selected": true },
{ "key": "key2", "selected": true },
{ "key": "key3", "selected": true }
]
}
},
methods: {
method1: function() {
var selectedKey = "";
this.myArray.forEach(function(item) {
// Obviously, accessing "this.someProp" here will not work
});
}
}
}
</script>
Example (working):
<script>
export default {
data() {
return {
myArray: [
{ "key": "key1", "selected": true },
{ "key": "key2", "selected": true },
{ "key": "key3", "selected": true }
]
}
},
methods: {
method1: function() {
var self = this; // Save "this" reference
var selectedKey = "";
self.myArray.forEach(function(item) {
// Here, accessing "self.someProp" will work since "this" was saved first.
});
}
}
}
</script>
My question is, is it possible to somehow specify "var self = this;" for all methods used in a component, without specifying it in each and every method? Somewhere on the start maybe? Probably cannot do it inside data
function since it requires this
modifier to be accessed.
Of course this is just a simple example, it could get more complex if, for example, calling some 3rd party libraries and providing them some callback functions where scope would be changed also.