Access properties within the Vue instance itself
Within a Vue.js instance, the keyword “this” points to an instance of a vue.js object. Therefore, the “this” reserved word is used to access instance properties, appended to the name of the desired property:
|
|
this.nazivSvojstvaVueInstance |
It should be noted that certain vue instance properties are specific, because they have additional “background magic” going on. The data, methods, computed and watch properties act as a “proxy for the vue instance”, so all properties inside them are passed directly to the vue instance. Therefore, all child properties of these specified properties are represented as if they were direct properties of the Vue instance.
Example
Thanks to this “magic”, when targeting child properties within those specific properties, we access them as if they were “main” properties. So we don’t need to use “this.data.someProperty”, we can just use “this.someProperty”.
|
|
var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, methods: { ispisiPoruku : function () { console.log (this.message); } } }) |
In this example, instead of using the this.data.message expression, we use this.message as a completely legitimate way.
Problem cases when using “this” (for: data, methods, computed and watch)
a) Arrow function
Child properties within these “special” properties (data, methods, computed and watch), precisely because of the “magic” in the background, should not use the arrow function because it uses the lexical “this” ie. uses “this” from the parent environment, so it would return “undefined” in that case. You can read more about the arrow function in the article “Arrow function”
b) Closure
If the clousure function is called by an external function, then the “default rule” is used when determining the value of the keyword “this” (read more about this in the article “Meaning of the “this” operator in JavaScript”). For the aforementioned reason the “this” keyword in the closure points to a global object.
Example
In this example this.message does not return the expected value but “undefined” because the global object does not have a “message” property
|
|
var app = new Vue({ el: "#app", data: { message: 'Message sent from closure!' }, methods: { ispisiPoruku : function () { function nekaClosure(){ return this.message; }; var a = nekaClosure() console.log(a); // Returnsundefined } } }) |
To solve this problem, we can use the well-known technique
var self = this;, where we save the value this within the new variable of the closure function (closure always has access to this variable). Read more about this mechanism in the section “Mechanism self=this”
See the Pen Closure within Vue.js by Web programming (@chos) on CodePen.
Read more