Vue 组件生命周期钩子没有被调用 [英] Vue Component Lifecycle Hooks Not Being Called

查看:115
本文介绍了Vue 组件生命周期钩子没有被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看此问题的示例此处.

我有一个 组件,它只显示一个计时器(当然,它每秒更新一次).如果我在页面上同时有三个这样的计时器,它们会按预期工作.但是,如果我有三个在不同时间显示在页面上(即使用 v-if 语句),则计时器无法按预期工作.第一个计时器工作正常,但后续计时器的生命周期钩子永远不会触发.我偷偷地怀疑 Vue 正试图变得聪明并重用我的第一个组件,因为它不再出现在页面上.我可以做些什么来解决这种行为?

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?

推荐答案

使用 key.

key 特殊属性主要用作 Vue 虚拟 DOM 算法的提示,以在将新节点列表与旧列表进行比较时识别 VNode.在没有键的情况下,Vue 使用一种算法来最小化元素移动并尝试尽可能多地就地修补/重用相同类型的元素.

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>

这篇关于Vue 组件生命周期钩子没有被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆