未调用 Vue 组件生命周期挂钩
Vue Component Lifecycle Hooks Not Being Called
查看此问题的示例 here。
我有一个 <count-down>
组件,它只显示一个计时器(当然每秒更新一次)。如果我在页面上同时有三个这样的计时器,它们会按预期工作。但是,如果我有三个在不同时间显示在页面上(即使用 v-if
语句),则计时器不会按预期工作。第一个计时器工作得很好,但后续计时器的生命周期挂钩永远不会触发。我偷偷怀疑 Vue 试图变得聪明并重用我的第一个组件,因为它不再在页面上了。我该怎么做才能解决此问题?
使用 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.
来自您的代码笔:
<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>
查看此问题的示例 here。
我有一个 <count-down>
组件,它只显示一个计时器(当然每秒更新一次)。如果我在页面上同时有三个这样的计时器,它们会按预期工作。但是,如果我有三个在不同时间显示在页面上(即使用 v-if
语句),则计时器不会按预期工作。第一个计时器工作得很好,但后续计时器的生命周期挂钩永远不会触发。我偷偷怀疑 Vue 试图变得聪明并重用我的第一个组件,因为它不再在页面上了。我该怎么做才能解决此问题?
使用 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.
来自您的代码笔:
<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>