Vue的生命周期

只要学过Vue的人,基本都能掌握Vue的生命周期,关于生命周期的文章有很多,面试Vue也一定会问到生命周期相关的知识点。那么,在我们理解了生命周期之后,怎么应用到我们的项目之中呢。
最常用的,我们会在created发起异步请求

...
created() {
  axios.get('some/path')
},
...

或者在mounted之后获取实际dom节点

...
mounted() {
  console.log(this.$el.offsetHeight)
},
...

或者是在beforeDestroy中清除定时器,或者注销一些变量,或者解绑一些事件

...
beforeDestroy() {
  clearTimeout(this.timer)
  this.foo = null
  this.somePlugin.destroy()
  window.removeEventListener('resize', this.resizeHandler)
}
...

最后这种情况,我们经常会遇到一个问题,我们在created或者mounted注册一些定时器,或者事件,却要在beforeDestroy中去清除或解绑。

created() {
  this.timer = setTimeout(() => { /* do something */ }, 10000)
},
beforeDestroy() {
  if (this.timer) {
    clearTimeout(this.timer)
  }
}
created() {
  this.handler = () => { /* code */ }
  window.addEventListener('resize', this.handler)
},
beforeDestroy() {
  window.removeEventListener('resize', this.handler)
}

这样导致我们代码的逻辑被分散,不利于平时的维护,我们可能只删除了created中的代码,却忘了beforeDestroy还有一部分相关的代码。
在这里我们可以利用Vue实例中的$once,我们稍微改一下代码

created() {
  const timer = setTimeout(() => { /* do something */ }, 10000)
  this.$once('hook:beforeDestroy', () => {
    clearTimeout(timer)
  })

  const handler = () => { /* code */ }
  window.addEventListener('resize', handler)
  this.$once('hook:beforeDestroy', () => {
    window.removeEventListener('resize', handler)
  })
}

这样就可以聚合我们的代码逻辑。

还有一种场景我们可能也遇到过,有时候我们需要获取子组件的实例或者dom节点

...
<div v-if="condition">
  <child ref="child" />
</div>
...
<script>
export default {
...
  mounted() {
    console.log(this.$refs.child)
  }
}
</script>

我们所预想的,这里应该是能获取到$refs.child,但我们往往忽略了外层还有一个condition,当它不成立时,child是不会初始化的,我们获取的往往也是一个undefiend。当然我们可以通过watch condition的值,来决定什么时候去获取$refs.child,但这样的话,在我们更改条件或不需要条件的时候,那么我们写在watch的逻辑也要相应的更改或移除,也是不利于我们维护。这里要介绍的是另外一种方式,在我们学习Vue事件绑定的时候,我们一定知道v-on(@),其实生命周期也会$emit事件。

...
<div v-if="condition">
  <child ref="child" @hook:mounted="childMounted" />
</div>
...
<script>
export default {
...
  methods: {
  ...
    childMounted() {
      console.log(this.$refs.child)
    }
  ...
}
</script>

通过这样的方式,也能在准确的时机去获取子组件的实例。在我们对child组件调整时,也不需要去调整childMounted的逻辑。

当然还有一些更高级的用法

Vue.mixin({
    beforeCreate () {
      if (isDef(this.$options.router)) {
        this._routerRoot = this
        this._router = this.$options.router
        this._router.init(this)
        Vue.util.defineReactive(this, '_route', this._router.history.current)
      } else {
        this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
      }
      registerInstance(this, this)
    },
    destroyed () {
      registerInstance(this)
    }
  })

这个是vue-router中的代码片段,全局mixin了两个生命周期,这也是为什么在使用vue-router之后,我们每个组件都能获取到$route$router

当然关于生命周期使用的技巧还有很多,欢迎补充。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。