Vue生命周期函数

今天小编继续和大家一起研究Vue,今天要一起探讨的是生命周期函数,在小编的理解中,生命周期就是在一定时间自动执行的函数,就类似原生js中的window.onload。
小编先拷贝一张来自Vue官方文档中的一张图
Vue生命周期函数_第1张图片
其实在这张图中,已经完整的说明了Vue中每个生命周期中的函数的执行时间,但是小编还是要用代码结合注释,更加详细的说明生命周期。

const app = Vue.createApp({
  data(){
    return {
      message: 'helllo world'
    }
  },
  methods:{
    handllItemClick(){ // 绑定点击事件。功能就是点击DOM元素的时候,更新data中的数据
      this.message = '666'
    }
  },
  // 在实例生成之前会自动执行的函数
  beforeCreate(){
    console.log('beforeCreate')
  },
  // 在实例生成之后会自动执行的函数
  created(){
    console.log('created')
  },

  // 在模板已经被变成函数之后立即执行的函数(在组件内容被渲染到组件之前自动执行的函数)
  beforeMount(){
    console.log(document.getElementById('root').innerHTML) // 空白
    console.log('beforeMount')
  },
  // 在组件内容被渲染到页面之后自动执行的函数
  mounted(){
    console.log(document.getElementById('root').innerHTML) // 
hello world
console.log('mounted') }, // 当data中的函数变化会立即自动执行的函数 beforeUpdate(){ console.log(document.getElementById('root').innerHTML) //
hello world
console.log('beforeUpdate') }, // 当data中的函数变化,同时页面完成更新后会自动执行的函数 updated(){ console.log(document.getElementById('root').innerHTML) //
666
console.log('updated') }, // 当Vue应用失效时,自动执行的函数 beforeUnmounted(){ console.log(document.getElementById('root').innerHTML) //
hello world
console.log('beforeUnmounted') }, // 当Vue应用失效时,且 data 数据完全销毁(DOM完全销毁)之后,自动执行的函数 unmounted(){ console.log(document.getElementById('root').innerHTML) // 空白 console.log('unmounted') }, template: '
{{ message }}
' }) const vm = app.mount('#root')

至于生命周期在实际项目中的使用,每个生命周期适合做哪些事情,小编会在今后的文章陆续更新,今天的目的就是要和生命周期函数混个脸熟。一起加油!
大家还可以扫描二维码,关注我的微信公众号,蜗牛全栈

你可能感兴趣的:(Vue生命周期函数)