菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
401
0

vue3.0 生命周期

原创
05/13 14:22
阅读数 90759

 在 scirpt引入:

import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured, ref, reactive } from 'vue'

在 setup 调用:

export default defineComponent ({
    setup() {
    onBeforeMount(() => { 
    });     onMounted(()
=> {
    });     onBeforeUpdate(()
=> {
    });     onUpdated(()
=> {
    });     onBeforeUnmount(()
=> {
    });     onUnmounted(()
=> {
    });     onErrorCaptured(()
=> {
    });     
return {     }   }, })

 

1、页面加载前 --- beforeMount:挂在开始之前被调用,相关的render函数首次被调用(虚拟DOM),实例已完成以下的配置: 编译模板,把data里面的数据和模板生成html,完成了el和data 初始化,注意此时还没有挂在html到页面上。

onBeforeMount() {
  console.log("App ===> 相当于 vue2.x 中 beforeMount")
},

2、挂载事件等 --- mounted:挂载完成,也就是模板中的HTML渲染到HTML页面中,此时一般可以做一些ajax操作,mounted只会执行一次。

onMounted() {
  console.log("App ===> 相当于 vue2.x 中 mounted")
},

3、数据更新前 --- beforeUpdate:在数据更新之前被调用,发生在虚拟DOM重新渲染和打补丁之前,可以在该钩子中进一步地更改状态,不会触发附加地重渲染过程。

onBeforeUpdate() {
  console.log("App ===> 相当于 vue2.x 中 beforeUpdate")
},

4、数据更新时候 --- updated:在由于数据更改导致地虚拟DOM重新渲染和打补丁只会调用,调用时,组件DOM已经更新,所以可以执行依赖于DOM的操作,然后在大多是情况下,应该避免在此期间更改状态,因为这可能会导致更新无限循环,该钩子在服务器端渲染期间不被调用。

onUpdated() {
  console.log("App ===> 相当于 vue2.x 中 updated")
},

5、页面销毁前 --- beforeDestroy:在实例销毁之前调用,实例仍然完全可用,

  1. 这一步还可以用this来获取实例,
  2. 一般在这一步做一些重置的操作,比如清除掉组件中的定时器 和 监听的dom事件。
onBeforeUnmount() {
  console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
},

6、页面销毁后 --- destroyed:在实例销毁之后调用,调用后,所以的事件监听器会被移出,所有的子实例也会被销毁,该钩子在服务器端渲染期间不被调用。

onUnmounted() {
  console.log("App ===> 相当于 vue2.x 中 destroyed")
},

7、错误处理机制 --- errorCaptured:指定组件的渲染和观察期间未捕获错误的处理函数。这个处理函数被调用时,可获取错误信息和 Vue 实例。

onErrorCaptured() {
  console.log("Counter ===> 相当于 vue2.x 中 errorCaptured")
}

 

Vue2.0 APIVue3.0 API (钩在里面 setup)
beforeCreate 不需要*
created 不需要*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

 

注:Vue3.0 的 setup,是围绕 beforeCreate 和 created 生命周期挂钩运行的,因此无需显式定义;也就是说,在这些挂钩中编写的任何代码,都应直接在setup函数中编写。

发表评论

0/200
401 点赞
0 评论
收藏
为你推荐 换一批