Vue生命周期

发布时间 2023-10-12 10:15:29作者: 3DG

Vue生命周期

什么是Vue生命周期

指的是Vue从创建到销毁整个过程

在官网中这样说到"每个 Vue 组件实例在创建时都需要经历一系列的初始化步骤"以及"在此过程中,它也会运行被称为生命周期钩子的函数,让开发者有机会在特定阶段运行自己的代码。"

官网图示如下

 

 

Vue生命周期函数

  • 初始化显示

    • beforeCreate()

    • created()

    • beforeMount()

    • mounted()

  • 更新状态:this.xxx=value

    • beforeUpdate()

    • updated()

  • 销毁Vue实例vm.%destory()

    • beforeDestory()

    • destoryed()

  • 注册生命周期钩子

    onMounted钩子可在组件完成初始渲染并创建DOM节点后运行代码

<script setup>
import { onMounted } from 'vue'
​
onMounted(() => {
  console.log(`the component is now mounted.`)
})
</script>

 

 
  • 常用方法

    1)mounted()

    发送AJAX请求、启动定时器、绑定自定义事件、订阅消息等异步任务(初始化操作)

    2)beforeDestroy()

    如: 清除定时器、解绑自定义事件、取消订阅消息等(收尾工作)

注意!

  • 生命周期函数的名字不可更改,但函数内容是由程序员根据需求编写

  • 生命周期函数中的 this 指向是 vm 或 组件实例对象

  • 销毁时注意

    1. 销毁后借助 Vue 开发者工具看不到任何信息

    2. 销毁后自定义事件会失效,但原生 DOM 事件依然有效

    3. 一般不会在 beforeDestroy 操作数据,因为即便操作数据,也不会再触发更新流程

<script>
        //创建一个Vue对象实例
        new Vue({
            el:'#root',//el用于指定当前Vue实例为哪个容器服务,值通常为css选择器(id选择器)
            data:{//data属性用于存储页面渲染的数据
                name:'3DG',
                address:'成都'
            },
            //Vue生命周期钩子函数
            beforeCreate(){
                console.log("调用beforeCreate");
            },
            created(){
                console.log("调用created");
            },
            beforeMount(){
                console.log("调用beforeMount");
            },
            mounted(){
                //vue创建完成,可完全使用vue兑现实现数据初始化工具
                console.log("调用mounted");
            },
            beforeUpdate(){
                console.log("调用beforeUpdate");
            },
            updated(){
                console.log("调用updated");
            },
            beforeDestroy(){
                console.log("调用beforeDestroy");
                alert("销毁前")
            },
            destroyed(){
                console.log("调用destrouyed");
                alert("销毁后")
            }
        })
    </script>