Vue-router: component event handler still active when vue-router swapped it out in vue2.0

Created on 7 Sep 2016  ·  3Comments  ·  Source: vuejs/vue-router

Vue.js & vue-router.js version

v2.0.0-rc.4 for both

Reproduction Link

https://jsfiddle.net/matiascx/32gu7u00/2/

Steps to reproduce

  1. click /home,
  2. click 'click me'
  3. click /foo
  4. click 'click me'
  5. click /home
  6. click 'click me'
    ### What is Expected?
    after 2nd step, there is a message "event received by Home component"
    after 4th step, since Home component is swapped out, the component should be destroyed and event handlers are removed also. Unfortunately, even Home is not active, the event handler is live, and there is a message of "event received by Home component" printed out;
    after 6th step, since the event handler registering is executed, so there should be ONE "event received by Home component" message printed. Strangely, there are 2 messages of "event received by Home component" printed out.
    ### What is actually happening?
    This should be a bug.
    When swapped out of the component by vue-router, the component should be destroyed and its event handler should be removed also. But now, it does not.
    Since the event registering of Home component is on the mounted() hook, they will be re-register again when Home is active again. That will bring un-necesary behaviour.

Most helpful comment

English: OP created an event bus manually and registered events to it. He has to take care to remove those events registrations again when the component gets destroyed, in the beforeDestroy or destroyed hook, because Vue cannot be responsible for events you manually set up with an event bus.

All 3 comments

全局bus需要你自己在destroyed钩子里$off。当时文档里没写,我看到忘了补,现在去补上。

(edit: Sorry for forgetting to use English, because I somehow remembered OP to be speaking Chinese.... For English version see below)

English: OP created an event bus manually and registered events to it. He has to take care to remove those events registrations again when the component gets destroyed, in the beforeDestroy or destroyed hook, because Vue cannot be responsible for events you manually set up with an event bus.

@fnlctrl ,多谢你的指点,确实如你所说,bug fixed
@LinusBorg ,thanks for your information, i have added the event de-registering function in the beforeDestroy hook, that works pretty well now!~

Was this page helpful?
0 / 5 - 0 ratings