undefinedfix
Sign in

Vue subcomponents are destroyed, but subcomponent instances are not destroyed (a deep problem)

nikolay edited in Wed, 27 Apr 2022

Problem: the destroyed hook function is executed in the Vue sub component, but the instance is not destroyed to share the known contents: 1. The Vue project assumes that there is only Vue router, If you switch a sub component (specific Vue file) in the primary route, it will be destroyed in the Vue file. At this time, I think this sub component has destroyed the object of this sub component. 2. If you switch this sub component in each primary route, you will continue to create new this object and destroy this object

Experimental scenario: a simple Vue single page system of login and home page. The login page and home page switch in the primary route. I write the following code in the created hook function of the home page:

clipboard.png

The timer will poll to get this object every other time. When I switch back and forth between login and home page, I will find that this timer prints out multiple this objects. Hehe, isn't it strange? Mingming was destroyed when switching, but why does the destroyed this object exist? What's wrong with that? That is to say, output the data attribute in the timer. When this attribute is initialized, it is a dynamically generated random number. You will find that the same attribute of this is composed of multiple contents....

There are also solutions, which can be called when switching back to login location.load To refresh, to clear.... But I really don't know what the principle is, which leads to the unexplained exception... Let me destroy the three outlooks, the dog

4 Replies
Ove
commented on Wed, 27 Apr 2022

Then the answer from upstairs added that the timer was to be destroyed

...
mounted() {
    this.timer = setInterval(() => {
        console.log(this);
    }, 30000);
},

destoryed() {
    clearInterval(this.timer);
}
Igorriok
commented on Wed, 27 Apr 2022

Your problem is that the timer is attached to the window, and the timer parameter is a function, which is a closure. The closure accesses the instance object this, so the window references the timer, the timer references the function, and the function references this, If the timer is not unloaded, this can be traversed by the window object and will not be recycled;

Yashu
commented on Wed, 27 Apr 2022

You call this a memory leak.

matt082606
commented on Wed, 27 Apr 2022

If you reference it in the timer, it will never be destroyed. How many times do you enter it, and how many times do you create it

lock This question has been locked and the reply function has been disabled.