Skip to content

peter-gy/vue3-v-for-memory-leak-repro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

Vue3 Memory Leak When Using v-for

Click here to open the Vue3 app in Vue SFC Playground.

Screencast

vue3-v-for-memory-leak.mp4

Synopsis

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>

Reproduction Steps

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.

  1. Open the app in MS Edge
  2. Open the DevTools and navigate to the "Detached Elements" tab
  3. Refresh the element state and force an initial garbage collection by clicking the trash icon
  4. Set the counter to 0
  5. Refresh the element state and force a garbage collection by clicking the trash icon again
  6. 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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published