DEV Community

Jihao Deng
Jihao Deng

Posted on

VUE003 Vue Lifecycle & Hooks

Vue的生命周期

Vue实例从创建和销毁的过程就是它的生命周期。

这一过程中会有一些关键时刻。比如渲染完成、初始化完成和被销毁。

Vue的生命周期钩子

对于生命周期中的关键时刻,我们可以以回调方法的方式进行回调,这就是生命周期钩子,被回调的方法叫做生命周期钩子函数

Vue生命周期图示

参考官网 https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

图中总共显示了8个红色的方框,包含看代表了8个生命周期钩子:

  • beforeCreate
  • created
  • beforeMount 数据被载入前
  • mounted 数据被载入后
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

生命周期钩子的用法

为了使用这些钩子,我们只需要在初始化Vue对象的时候重写这些方法即可:

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      message: "Hello, Vue World!"
    }
  },
  beforeCreate: function () {
    console.log("a message in beforeCreate  " + this.message)
  },
  created: function() {
    console.log("a message in created  " + this.message)
  },
  beforeMount: function() {
    console.log("a message in beforeMount  " + this.message)
  },
  mounted: function() {
    console.log("a message in mounted  " + this.message)
  }
})
Enter fullscreen mode Exit fullscreen mode

对于上述代码,beforeCreate中因为message还没有被创建出来,所以会输出undefined,其他三个都会输出data里面的Hello, Vue World!

这些钩子都是通过this指针来访问Vue对象里面的数据,所以,我们不能使用箭头函数来重写钩子,因为箭头函数并不能用this访问我们的Vue对象。

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay