Search code examples
javascriptvue.jsgarbage-collection

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?


Solution

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