Vue实例之生命周期

这篇博客详细介绍了Vue实例的生命周期,包括beforeCreate、created、beforeMount、mounted、beforeUpdate、updated、beforeDestroy和destroyed等各个阶段,以及在这些阶段可以进行的操作。特别提到了在created和beforeMount之间进行数据初始化,而在mounted阶段可以操作真实DOM。还讨论了嵌套组件内生命周期的执行顺序,指出beforeCreate、created、beforeMounted是由外到内,而mounted则是由内到外的顺序执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue的基本生命周期

       每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。

       在vue一整个的生命周期中会有很多钩子函数提供给我们在vue生命周期不同的时刻进行操作, 那么先列出所有的钩子函数,然后我们再一一详解:

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

首先看代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../../vue.js"></script>
</head>
<body>
  <div id="app">
    {{username}}
  </div>
  <script>
    var vm = new Vue({
      el: "#app",
      data: {
        username: 'aaa'
      },
      beforeCreate() {
        console.log("beforeCreate:", this.username)
      },
      created() {
        console.log('created:', this.username)
      },
      beforeMount() {
        console.log('before mount')
        console.log(document.getElementById("app"))
        this.username = "bbb";
      },
      mounted() {
        console.log('mounted:');
        console.log(document.getElementById("app"))
        console.log(this.$el)
        setTimeout(() => {
          vm.$destroy();
        }, 3000)
      },
      beforeUpdate() {
        console.log('beforeUPdate')
      },
      updated() {
        console.log('updated')
      },
      beforeDestroy() {
        console.log('beforeDestroy')
      },
      destroyed() {
        console.log('destroyed')
      }
    })
  </script>
</body>
</html>

输出结果为:

在beforeCreate和created钩子函数之间的生命周期

       在这个生命周期之间,进行初始化事件,进行数据的观测,可以看到在created的时候数据已经和data属性进行绑定(放在data中的属性当值发生改变的同时,视图也会改变)。此时还是没有el选项。能拿到data下的数据,能修改data的数据 修改数据不会触发updated , beforeUpdate 钩子函数 取不到最终渲染完成的dom 。在实例初始化之后,数据观测和事件配置之前被调用,此时组件的选项对象还未创建,el 和 data 并未初始化,因此无法访问methods, data, computed等上的方法和数据。created周期,实例已经创建完成之后被调用,在这一步,实例已完成以下配置:数据观测、属性和方法的运算,watch/event事件回调,完成了data 数据的初始化,el没有。 然而,挂在阶段还没有开始, $el属性目前不可见,这是一个常用的生命周期,因为你可以调用methods中的方法,改变data中的数据,并且修改可以通过vue的响应式绑定体现在页面上,获取computed中的计算属性等等,通常我们可以在这里对实例进行预处理,

created钩子函数和beforeMount间的生命周期

        首先会判断对象是否有el选项。如果有的话就继续向下编译,如果没有el选项,则停止编译,也就意味着停止了生命周期,直到在该vue实例上调用vm.$mount(el)。编译模板已经结束 可以访问data数据 可以修改数据,修改数据不会触发updated , beforeUpdate 钩子函数 。

beforeMount和mounted 钩子函数间的生命周期

       此时是给vue实例对象添加$el成员,并且替换掉挂在的DOM元素。beforeMount,挂在开始之前被调用,相关的render函数首次被调用(虚拟DOM),实例已完成以下的配置: 编译模板,把data里面的数据和模板生成html,完成了el和data 初始化,注意此时还没有挂在html到页面上。

mounted

      真实的dom节点已经渲染到页面,可以操作渲染后的dom 可以访问和更改数据,会触发updated , beforeUpdate 钩子函数。

beforeUpdate钩子函数和updated钩子函数间的生命周期

      当vue发现data中的数据发生了改变,会触发对应组件的重新渲染。beforeUpdate,在数据更新之前被调用,发生在虚拟DOM重新渲染和打补丁之前,可以在该钩子中进一步地更改状态,不会触发附加地重渲染过程。updated(更新后),在由于数据更改导致地虚拟DOM重新渲染和打补丁只会调用,调用时,组件DOM已经更新,所以可以执行依赖于DOM的操作,然后在大多是情况下,应该避免在此期间更改状态,因为这可能会导致更新无限循环,该钩子在服务器端渲染期间不被调用
beforeDestroy和destroyed钩子函数间的生命周期

     beforeDestroy钩子函数在实例销毁之前调用。在这一步,实例仍然完全可用。destroyed钩子函数在Vue 实例销毁后调用。调用后,Vue 实例指示的所有东西都会解绑定,所有的事件监听器会被移除,所有的子实例也会被销毁。在实例销毁之前调用,实例仍然完全可用,这一步还可以用this来获取实例,一般在这一步做一些重置的操作,比如清除掉组件中的定时器 和 监听的dom事件。

嵌套组件内的生命周期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <title>嵌套组件的生命周期</title>
</head>
<body>
    <div id="app">
        <component-a />
    </div>   
 
    <script>
        Vue.component('component-a', {
            template: '<div><component-b></component-b></div>',
            beforeCreate () {
                console.log('beforeCreate: A');
            },
            created() {
                console.log('created: A');
            },
            beforeMount() {
                console.log('beforeMount: A');
            },
            mounted() {
                console.log('mounted: A');
            },
        });
 
        Vue.component('component-b', {
            template: '<p><component-c></component-c></p>',
            beforeCreate () {
                console.log('beforeCreate: B');
            },
            created() {
                console.log('created: B');
            },
            beforeMount() {
                console.log('beforeMount: B');
            },
            mounted() {
                console.log('mounted: B');
            },
        });
 
        Vue.component('component-c', {
            template: '<span>hello world</span>',
            beforeCreate () {
                console.log('beforeCreate: C');
            },
            created() {
                console.log('created: C');
            },
            beforeMount() {
                console.log('beforeMount: C');
            },
            mounted() {
                console.log('mounted: C');
            },
        });
 
        const app = new Vue({
            el: '#app',
            beforeCreate () {
                console.log('beforeCreate: Root');
            },
            created() {
                console.log('created: Root');
            },
            beforeMount() {
                console.log('beforeMount: Root');
            },
            mounted() {
                console.log('mounted: Root');
            }
        });
    </script>
</body>
</html>

打印结果为:

        通过打印结果我们可以看到,beforeCreate、created、beforeMounted是按顺序执行,由外到内;而mounted即最终的挂载阶段则是由内到外,先将子组件挂载到dom上,然后再是父组件

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值