【问题标题】:Vue.js: Is there a way to know when the component instance is mounted?Vue.js:有没有办法知道组件实例何时挂载?
【发布时间】:2019-07-31 11:15:24
【问题描述】:

是否有我们可以在每个组件实例中访问的布尔值来了解组件何时挂载?

类似:

<template>
  <div>
    <span v-if="$mounted">I am mounted</span>
    <span v-if="$created">I am created</span>
    <span>Called before created and mounted</span>
  </div>
</template>

【问题讨论】:

  • 当然。使用本机提供给您的 mountedcreatedbeforeCreate 函数。看看vue life-cycle diagram

标签: vue.js vuejs2


【解决方案1】:

2020 年更新

Vue.js 有一个未记录的功能,您可以在其中知道组件的生命周期挂钩何时执行:Source

语法如下:

<ChildComponent @hook:lifecycleHookName="callAMethod" />

示例:

如何知道子组件何时挂载:

<ChildComponent @hook:mounted="componentMountedDoSomething" />

如何知道子组件何时创建:

<ChildComponent @hook:created="componentCreatedDoSomething" />


<template>
  <div>
    <span v-if="mounted">I am mounted</span>
    <span v-if="created">I am created</span>
    <span>Called before created and mounted</span>
  </div>
</template>

还有脚本:

export default {
  data: () => ({
    created: false,
    mounted: false
  }),
  created () {
    this.created = true
  },
  mounted() {
    this.mounted = true
  }
}

【讨论】:

  • 谢谢,这就是我的想法。我希望 Vue 有一个公共布尔值可以用来避免这些行。 :)
  • 这取决于你想要达到的目标。 Bc 上面的代码我不明白你在做什么。但是IMO那里的线路并不多。
  • 有,但由于它不在官方文档中,它可能不是依赖它的最佳方式。但是如果你检查VueInstance 对象,你会发现_isMounted_isBeingDestroyed等。布尔值。 created 是隐含的,因为甚至有一个可用的 vue 实例。
【解决方案2】:

是的,使用生命周期挂钩。

new Vue({
  data: {
    a: 1
  },
  created() {
    // `this` points to the vm instance
    console.log('a is: ' + this.a)
  },
  mounted() {
    console.log("i am mounted in dom");
  }
})

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多