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

本小妞迷上赌 提交于 2020-01-02 02:32:05

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/59443388/why-doesnt-an-unassigned-vue-instance-get-garbage-collected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!