日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

Vue3生命周期鉤子函數詳解_vue.js

作者:葉子_o ? 更新時間: 2022-04-07 Vue

本文實例為大家分享了Vue3生命周期鉤子函數的具體代碼,供大家參考,具體內容如下

一、Vue3生命周期鉤子

setup() : 開始創建組件之前,在 beforeCreate created 之前執行,創建的是 data method
onBeforeMount() : 組件掛載到節點上之前執行的函數;
onMounted() : 組件掛載完成后執行的函數;
onBeforeUpdate(): 組件更新之前執行的函數;
onUpdated(): 組件更新完成之后執行的函數;
onBeforeUnmount(): 組件卸載之前執行的函數;
onUnmounted(): 組件卸載完成后執行的函數;
onActivated(): 被包含在 <keep-alive> 中的組件,會多出兩個生命周期鉤子函數,被激活時執行;
onDeactivated(): 比如從 A 組件,切換到 B 組件,A 組件消失時執行;
onErrorCaptured(): 當捕獲一個來自子孫組件的異常時激活鉤子函數。
PS: 使用<keep-alive> 組件會將數據保留在內存中,比如我們不想每次看到一個頁面都重新加載數據,就可以使用<keep-alive> 組件解決。

二、Vue2.x 和 Vue3.x 生命周期對比

三、Vue3生命周期鉤子函數的簡單使用

<template>
? <div>
? ? <h1>Vue3生命周期鉤子函數</h1>
? ? <h2>響應式攔截數據data的值是:{{msg}}</h2>
? ? <p><button @click="changeMsg">點擊改變msg</button></p>
? </div>
</template>

<script>
import { reactive, onUnmounted, onUpdated, onMounted, toRefs } from 'vue'; // 引入需要的
export default {
? setup () {
? ? // 初始化項目工作都放在setup中
? ? console.log("當前應用程序被安裝了");
? ? const state = reactive({ // 定義狀態
? ? ? msg: '學而時習之', // 定義變量
? ? ? changeMsg: () => { // 定義方法
? ? ? ? state.msg = '不亦說乎'
? ? ? }
? ? })
? ? let timer = 0;
? ? let count = 0;
? ? onMounted(() => {
? ? ? console.log('頁面掛載完成,觸發了onMounted鉤子函數');
? ? ? timer = setInterval(() => {
? ? ? ? console.log('定時器正在運行中', count++)
? ? ? }, 1000)
? ? })
? ? onUpdated(() => {
? ? ? console.log('數據發生了更新,觸發了onUpdated鉤子函數')
? ? })
? ? onUnmounted(() => {
? ? ? console.log('頁面/組件退出,觸發了onUnmounted鉤子函數')
? ? ? // 如果不清楚,這些異步的行為就會常駐在內存中,一定程度上會造成常駐內存的不必要消耗,造成內存泄露
? ? ? clearInterval(timer);
? ? })
? ? return {
? ? ? ...toRefs(state)
? ? }
? }
}
</script>

原文鏈接:https://blog.csdn.net/xiamoziqian/article/details/111157438

欄目分類
最近更新