Here's the standard way to use VueJS on the HTML page (without bundles). No assignment.
<script>
new Vue({
el: '#root',
data: {
title: 'Hello'
}
});
</script>
Why Garbage Collector doesn't collect this Vue object?
Here's the standard way to use VueJS on the HTML page (without bundles). No assignment.
<script>
new Vue({
el: '#root',
data: {
title: 'Hello'
}
});
</script>
Why Garbage Collector doesn't collect this Vue object?
Share Improve this question edited Dec 26, 2019 at 20:49 ux.engineer 11.4k15 gold badges69 silver badges114 bronze badges asked Dec 22, 2019 at 10:24 sklskl 1037 bronze badges 3- Because something like keep-alive exists. – Eldar Commented Dec 22, 2019 at 11:00
- 1 How do you know that GC doesn't collect the un-assigned Vue instance object? This ment in relation to Vue Router indicates how Router gets collected when used without assignment (it's a general functionality of GC to collect such unassigned instances, however GC implementations may vary across different browsers): stackoverflow./a/30319602/2442714 – ux.engineer Commented Dec 25, 2019 at 14:09
- What makes you think that it is not garbage-collected? – Bergi Commented Dec 25, 2019 at 14:41
2 Answers
Reset to default 5 +100When you instantiate a Vue object, it actually mounts itself to the DOM element, here #root
element, as briefly hinted in this documentation page The Vue Instance > Instance Lifecycle Hooks.
By using Developer Tools in your browser, like in Chrome, you can open the console tab and prompt, type console.log(window.$vm0);
and hit enter. And you get access to your Vue runtime instance even it was not assigned to a variable:
> Vue {_uid: 2, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: Vue, …}
I've opened another question on how to properly access the Vue instance if it wasn't assigned to a variable during instantiation.
The main point, as an answer to this current question, is that there is actually variable assignment / DOM mounting happening behind the scenes by Vue itself, so that is why garbage collection is not triggering.
PS. There is a detailed documentation article Avoiding Memory Leaks in relation to handling Garbage Collection in a Vue application.
A Vue application consists of a Vue instance created with new Vue and mounted in DOM element with id '#root'. Vue is running all this magic behind the scene that's why garbage collector will not collect Vue object.
In addition to data properties, Vue instances expose a number of instance properties and methods. These are prefixed with $ to differentiate them from user-defined properties. For example:
var data = { title: 'Hello' }
var vm = new Vue({
el: '#root',
data: data
});
// If you check below code
vm.$data === data // => true
vm.$el === document.getElementById('root') // => true