1👍
this whole code makes a Vue Component. In a Vue Component, initial data
should be a function, which will be invoked when component created. the object that returned by data()
is the initial data for the component, and it’s observable(observable
means, if you change it, something other will be changed also). the techniche of javascript used here is Object.defineProperty
: https://v2.vuejs.org/v2/guide/reactivity.html
base on your code, it says you have a initial data named ‘myVar’, if you change the value of ‘myVar’, the dom which bound with ‘myVar’ will change automatically. in your code, it’s the text of the button
.
mounted
this is a life-cycle hook, it will be invoked after the component mounted into the dom.
you called an AJAX at here, then you used arrow function to deal with the result of AJAX. arrow function
means it’s this
will not change (here , this
equals the Vue Component).
we already have a initial data ‘myVar’ on this component, now we change it:
this.myVar = response.data;
because it’s observable/reactive, the text of the button
in your template will be changed.
by the way, your initial myVar
is null, so your initial text myVar.name
will cause an error
0👍
// 'response' is the JSON data gotten from the backend:
....then(response => {
this.myVar = response.data;
});
In this first method, you are fetching data from a server, and assigning it this.myVar (not myVar). so it’s local to the component, however…
In the code below, whenever you call data(), you are returning an object with a property myVar encapsulated in it. it is not the same as this.myVar.
// 'myVar' is initialised here:
data: function() {
return {
myVar: null
};
}
I’m not sure what you’re trying to achieve here, but these variables are unrelated. And maybe the naming needs some work too, so it’s easier for us to see what the purpose of this code is. Either way, if this.myVar is a variable owned by your component, the object returned from the data() method will not have any effect on it, since it’s structure is different. the myVar in the Object you are returning in data is a new variable, local to that object.