/ vuejs / 5766浏览

Vue生命周期钩子

一个框架最重要的就是他的生命周期,掌握了其生命周期是理解进阶一个框架的必要。
以下列举所有的生命周期钩子以及其调用的时机:

const app = new Vue({
  el: '#root',
  template: '<div>{{text}}</div>',
  data: {
    text: 0
  },
  // Vue 实例化之前
  beforeCreate() {
    console.log(this.$el, 'beforeCreate')
  },
   // Vue实例化完成
  created() {
    console.log(this.$el, 'created')
  },
  //  DOM挂载之前
  beforeMount() {
    console.log(this.$el, 'beforeMount')
  },
  // 此时DOM挂载,可进行DOM操作;不会在服务端渲染
  mounted() {
    console.log(this.$el, 'mounted')
  },
 //  data更新前
  beforeUpdate() {
    console.log(this, 'beforeUpdate')
  },
  // 虚拟DOM重新渲染并应用更新
  updated() {
    console.log(this, 'updated')
  },
  // 当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行
  activated() {
    // 与keep alive有关
    console.log(this, 'activated')
  },
  deactivated() {
    // 与keep alive有关
    console.log(this, 'deactivated')
  },
 // 组件销毁前
  beforeDestroy() {
    console.log(this, 'beforeDestroy')
  },
  // 组件销毁
  destroyed() {
    console.log(this, 'destroyed')
  },
  // beforeMount与mounted之间
  render(h) {
    // throw new TypeError('render error')
    // console.log('render function invoked')
    return h('div', {}, this.text)
  },
  // render方法报错会调用此函数,会将出错误渲染到页面上,只会在调用此函数的组件中调用
  renderError(h, err) {
    return h('div', {}, err.stack)
  },
  // 任何组件报错都会捕获到
  errorCaptured() {
    // 会向上冒泡,并且正式环境可以使用
  }
})

父子组件生命周期的调用顺序

F代表father,S代表son。
请牢记,不然会…

F beforeCreate
F created
F beforeMount
S beforeCreate
S created
S beforeMount
S mounted
F mounted

更新于
vue-router
vue-router

0

  1. This post has no comment yet

发表回复