Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't an unassigned Vue instance get garbage collected?

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?

like image 776
skl Avatar asked Dec 22 '19 10:12

skl


2 Answers

When 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.

like image 81
ux.engineer Avatar answered Oct 10 '22 00:10

ux.engineer


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
like image 44
Yogi Avatar answered Oct 10 '22 00:10

Yogi