您的位置:首页 - 文章 - 前端 - 正文

Vue的常用钩子函数

vue有8种生命周期函数:

钩子函数 触发的行为 在此阶段可以做的事情
beforeCreadted vue实例的挂载元素$el和数据对象data都为undefined,还未初始化。 加loading事件
created vue实例的数据对象data有了,$el还没有 结束loading、请求数据为mounted渲染做准备
beforeMount vue实例的$el和data都初始化了,但还是虚拟的dom节点,具体的data.filter还未替换。 ..
mounted vue实例挂载完成,data.filter成功渲染 配合路由钩子使用
beforeUpdate data更新时触发
updated data更新时触发 数据更新时,做一些处理(此处也可以用watch进行观测)
beforeDestroy 组件销毁时触发
destroyed 组件销毁时触发,vue实例解除了事件监听以及和dom的绑定(无响应了),但DOM节点依旧存在 组件销毁时进行提示

测试代码:

export default {
  data () {
    return {
      todos: [],
      allCounts: 0,
      filter: 'all',
      id: 0,
      states: ['all', 'active', 'completed']
    }
  },
  beforeCreate () {
    console.log('==============' + 'beforeCreated' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  created () {
    console.log('==============' + 'created' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  beforeMount () {
    console.log('==============' + 'beforeMount' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  mounted () {
    console.log('==============' + 'mounted' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  beforeUpdate () {
    console.log('==============' + 'beforeUpdate' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  updated () {
    console.log('==============' + 'updated' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  beforeDestroy () {
    console.log('==============' + 'beforeDestroy' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  },
  destroyed () {
    console.log('==============' + 'destroyed' + '===================')
    console.log(this.$el)
    console.log(this.$data)
    console.log(this.filter)
  }
 }

效果:
刷新vue项目时
改变data中的filter时

本文原创,作者:西决,其版权均为品创网络所有。如需转载,请注明出处:https://www.sxpcwlkj.com/vue/

发表评论