Subscribe on changes!

It is hoped that the emit event can still be received after the component is destroyed

avatar
May 29th 2023

What problem does this feature solve?

我看3.2.33版本更新日志有一条: I see that there is an entry in the update log of version 3.2.33:

runtime-core: ensure custom events are not emitted anymore after unmount. (https://github.com/vuejs/core/issues/5679) (71c9536), closes https://github.com/vuejs/core/issues/5674

我希望能增加一个配置项,能让组件销毁后外面也能够正常接收到emit的事件。 I hope to add a configuration item, so that the outside can normally receive the emit event after the component is destroyed.

因为有些场景可能还是需要这样,比如我基于了vue组件的生命周期写了一个地图组件,在组件创建时初始化了地图实例viewer,在组件销毁的时候去销毁了这个地图实例viewer。等viewe销毁后再emit的事件,外部都接收不了。

Because some scenarios may still need this, for example, I wrote a map component based on the life cycle of the Vue component, initialized the map instance viewer when the component was created, and destroyed the map instance viewer when the component was destroyed. The event that emits after the viewe is destroyed cannot be received by the outside world.

What does the proposed API look like?

non

avatar
May 29th 2023

Normally, after the instance of the component is destroyed, it should be garbage collected, so the emit event cannot be monitored, but if you manually destroy the map instance, you can choose not to destroy it, and you can use EventBus to trigger, it It is unreasonable behavior to listen to events and let destroyed components trigger events.

avatar
May 29th 2023

Ok, then I'll consider using mitt to do it myself.

avatar
May 29th 2023

You could try to find the $parent and then call the method in the parent. You also could use provide/inject to pass the value if it's a deeply nested component.

avatar
May 30th 2023

Using a custom event emitter would be a better way to go. Vue won't support that

avatar
May 30th 2023

It is possible to use custom event, but it is really troublesome and cannot be bound to vue components. But I found a method that may not be conventional, which can continue to trigger events when the vue component is destroyed.

const instance = getCurrentInstance()
instance.isUnmounted = false