Click here to open the Vue3 app in Vue SFC Playground.
vue3-v-for-memory-leak.mp4
Consider this simple Vue app. It has a counter and a list of items. The list of items is generated using v-for
and Array.from
. When the counter is changed, the list of items is updated.
When the counter is changed, the list of items is updated. However, the old HTML nodes used to render the initial list of items become detached elements and keep lingering in memory, causing a memory leak.
<template>
<div>
<label for="counter">Counter</label>
<input id="counter" type="number" v-model="counter" />
<div v-for="n in items" :key="n">Item {{ n }}</div>
</div>
</template>
<script>
export default {
data() {
return {
counter: 5,
};
},
computed: {
items() {
if (!this.counter) return [];
return Array.from({ length: this.counter }, (_, i) => i + 1);
},
},
};
</script>
You can start the Vue3 app by running the following commands:
cd v-for-vue3 && npm i && npm run dev
Using MS Edge makes it easier to investigate the detached elements, so it is recommended to use it for reproduction. Learn more about how to use the Edge DevTools to investigate memory leaks here.
- Open the app in MS Edge
- Open the DevTools and navigate to the "Detached Elements" tab
- Refresh the element state and force an initial garbage collection by clicking the trash icon
- Set the counter to 0
- Refresh the element state and force a garbage collection by clicking the trash icon again
- See that the detached elements are still there
You can verify that this was not the case in Vue2. You can start the very same app in Vue2 by running the following commands:
cd v-for-vue2 && npm i && npm run dev