Vue Component Lifecycle Hooks Not Being Called

2019-07-31 23:27发布

See and example of this issue here.

I have a <count-down> component that simply displays an timer (that updates every second, of course). If I have three such timers on the page all at the same time, they work as expected. However, if I have three that are displayed on the pages at different times (i.e. using v-if statements), the timers don't work as expected. The first timer works just fine, but the lifecycle hooks for subsequent timers never fire. I have a sneaky suspicion that Vue is trying to be clever and reuse my first component, since it's no longer on the page any more. What can I do to work around this behavior?

1条回答
Viruses.
2楼-- · 2019-07-31 23:30

Use a key.

The key special attribute is primarily used as a hint for Vue’s virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible.

From your codepen:

  <count-down :description="'Timer 1: '" :seconds="3" v-if="sync" :key="1"></count-down>
  <count-down :description="'Timer 2: '" :seconds="5" v-if="sync" :key="2"></count-down>
  <count-down :description="'Timer 3: '" :seconds="7" v-if="sync" :key="3"></count-down>

  <count-down :description="'Timer 4: '" :seconds="3" v-if="async === 4" :key="4"></count-down>
  <count-down :description="'Timer 5: '" :seconds="5" v-if="async === 5" :key="5"></count-down>
  <count-down :description="'Timer 3: '" :seconds="7" v-if="async === 6" :key="6"></count-down>
查看更多
登录 后发表回答