Paleo
Paleo

Reputation: 23712

Is it a memory leak of Vue.js?

Here is the code of a component:

import { defineComponent, ref } from "@vue/composition-api";

const template = /* html */ `
<div>
  <nav>
    <button @click="showCanvas = !showCanvas">Toggle</button>
  </nav>a
  <canvas v-if="showCanvas" width="1000" height="1000" style="width: 50%; height: auto; background-color: #eee"></canvas>
</div>
`;

export default defineComponent({
  name: "SimpleIf",
  template,
  setup() {
    return {
      showCanvas: ref(true)
    };
  }
});

There is just a <canvas>, with a <button> that shows or hides the canvas.

I use Vue 2 with the composition API.

In Firefox, I open the dev tools. In the "Memory" tab, I take a snapshot. I set the view to "Aggregate" and I filter with "Canvas":

Screenshot before

The number of HTMLCanvasElement is 1. Now, I click on the button several times then I take a snapshot again:

Screenshot after

The number of HTMLCanvasElement is 9.

Why?

Notice: I made this test because I have an unexplained memory leak with huge canvas in a real application. I would like to understand how Vue cleans unused DOM elements and why mine still are in memory.

Upvotes: 0

Views: 1674

Answers (1)

Alex Brohshtut
Alex Brohshtut

Reputation: 2060

Did a bit of research in a sandbox in both - Chrome and Firefox, there are definitely new Canvas elements being created, however they are properly removed after some time - when Garbage Collector collects them (you can force FF to do it from about:memory page). Can't reproduce the leak longer than 20-30 seconds.

As far as I know, Vue doesn't reuse the v-if elements, it is always recreated. So may be try with v-show instead?

Upvotes: 3

Related Questions