Reputation: 186
When a function is used outside the vue instance and passed inside method mounted, why is the reference to 'vm' lost?
https://jsfiddle.net/z9u39hgu/5/
var vm = new Vue({
el: '#app-4',
data: {
isLoading: true
},
mounted: function() {
hello();
}
});
function hello() {
console.log(JSON.stringify(vm));
//vm.isLoading = true;
setTimeout(function() {
console.log(JSON.stringify(vm, replacer));
//vm.isLoading = false;
})
}
//Extra code ignore
seen = [];
var replacer = function(key, value) {
if (value != null && typeof value == "object") {
if (seen.indexOf(value) >= 0) {
return;
}
seen.push(value);
}
return value;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app-4">
<p v-if="isLoading">Vuejs loading...</p>
</div>
Upvotes: 0
Views: 917
Reputation: 421
It seems that mounted()
is fired from the Vue constructor, i.e. before the vm
variable can be even assigned. So the vm
reference is not lost, but it is still undefined when hello()
is called.
The timeout()
callback is called later when the Vue
constructor already returned and vm
variable is assigned. The chronology of these events is also visible in the console.
var vm = new Vue({
el: '#app-4',
data: {
isLoading: true
},
mounted: function() {
hello();
}
});
function hello() {
console.log("before timeout: " + typeof(vm));
//vm.isLoading = true;
setTimeout(function() {
console.log("after timeout: " + typeof(vm));
//vm.isLoading = false;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app-4">
<p v-if="isLoading">Vuejs loading...</p>
</div>
Upvotes: 4