東營建站公司seminar是什么意思
鶴壁市浩天電氣有限公司
2026/01/22 10:18:44
東營建站公司,seminar是什么意思,廣東模板建站平臺,東莞網(wǎng)站建設(shè)手袋加工目錄一、Vue的生命周期階段二、生命周期鉤子函數(shù)1、創(chuàng)建階段1、beforeCreate2、created #xff08;常用#xff09;2、掛載階段1、beforeMount2、 mounted3、更新階段1、beforeUpdate2、updated4、銷毀階段1、beforeDestroy2、destroyed一、Vue的生命周期階段
vue生命周期分…目錄一、Vue的生命周期階段二、生命周期鉤子函數(shù)1、創(chuàng)建階段1、beforeCreate2、created 常用2、掛載階段1、beforeMount2、 mounted3、更新階段1、beforeUpdate2、updated4、銷毀階段1、beforeDestroy2、destroyed一、Vue的生命周期階段vue生命周期分為四個階段第一階段創(chuàng)建階段beforeCreatecreated第二階段掛載階段beforeMountrendermounted第三階段更新階段beforeUpdateupdated第四階段銷毀階段beforeDestroydestroyed二、生命周期鉤子函數(shù)1、創(chuàng)建階段1、beforeCreate在實例初始化之后,進行數(shù)據(jù)偵聽和事件/偵聽器的配置之前同步調(diào)用。作用核心初始化Vue實例的響應式系統(tǒng)beforeCreate(){// 此時Vue實例的響應式系統(tǒng)還未建立}作用初始化事件系統(tǒng)和生命周期數(shù)據(jù)觀測 (data observation) 還未開始計算屬性 (computed) 和方法 (methods) 還未定義應用場景exportdefault{beforeCreate(){// ? 場景1記錄性能時間點this.$options.startTimeperformance.now();// ? 場景2初始化非響應式數(shù)據(jù)this.staticConfig{version:1.0.0,apiBaseUrl:process.env.API_URL};// ? 場景3預加載資源如圖片、字體constpreloadImages[/images/loading.gif,/images/error.png];preloadImages.forEach(src{constimgnewImage();img.srcsrc;});// ? 不能做的事情// console.log(this.message); // undefined// this.fetchData(); // undefined}}2、created 常用在實例創(chuàng)建完成后被立即同步調(diào)用。在這一步中實例已完成對選項的處理意味著以下內(nèi)容已被配置完畢數(shù)據(jù)偵聽、計算屬性、方法、事件/偵聽器的回調(diào)函數(shù)。然而掛載階段還沒開始且 $el property 目前尚不可用。解釋在這個階段可以訪問到數(shù)據(jù)了但是頁面當中真實dom節(jié)點還是沒有渲染出來在這個鉤子函數(shù)里面可以進行相關(guān)初始化事件的綁定、發(fā)送請求操作。created(){// 此時響應式系統(tǒng)已建立完成}作用數(shù)據(jù)觀測已完成屬性和方法已配置計算屬性已計算但DOM還未生成$el屬性不可用應用場景exportdefault{data(){return{user:null,settings:{},productList:[]};},created(){// 場景1發(fā)起異步數(shù)據(jù)請求最常用this.fetchInitialData();// 場景2從本地存儲讀取數(shù)據(jù)this.loadFromLocalStorage();// 場景3初始化組件狀態(tài)this.initComponentState();// 場景4設(shè)置事件總線監(jiān)聽this.setupEventBusListeners();// 場景5初始化第三方服務配置this.initThirdPartyServices();},methods:{asyncfetchInitialData(){try{// 并行請求多個接口const[userRes,settingsRes,productsRes]awaitPromise.all([axios.get(/api/user/profile),axios.get(/api/user/settings),axios.get(/api/products)]);this.useruserRes.data;this.settingssettingsRes.data;this.productListproductsRes.data;}catch(error){this.handleError(error);}},loadFromLocalStorage(){// 從本地存儲恢復狀態(tài)constsavedCartlocalStorage.getItem(shoppingCart);if(savedCart){this.cartItemsJSON.parse(savedCart);}// 讀取用戶偏好constthemelocalStorage.getItem(theme)||light;this.currentThemetheme;},initComponentState(){// 根據(jù)URL參數(shù)初始化constquerythis.$route.query;if(query.category){this.activeCategoryquery.category;}// 設(shè)置默認值this.pagination{page:1,pageSize:20,total:0};},setupEventBusListeners(){// 監(jiān)聽全局事件this.$eventBus.$on(user-logged-in,this.handleUserLogin);this.$eventBus.$on(notification,this.showNotification);},initThirdPartyServices(){// 初始化分析工具if(window.analytics){window.analytics.identify(this.userId);}// 初始化錯誤監(jiān)控if(window.Sentry){window.Sentry.configureScope(scope{scope.setUser({id:this.userId});});}}}}核心要點可以訪問所有響應式數(shù)據(jù)適合數(shù)據(jù)初始化工作不能操作DOM請求數(shù)據(jù)的最佳時機減少白屏時間2、掛載階段1、beforeMount作用核心將模板編譯并掛載到真實DOM在掛載開始之前被調(diào)用相關(guān)的 render 函數(shù)首次被調(diào)用。解釋代表dom馬上就要被渲染出來了但是卻還沒有真正的渲染出來這個鉤子函數(shù)與created鉤子函數(shù)用法基本一致可以進行相關(guān)初始化事件的綁定、發(fā)送ajax操作。2、 mounted掛載階段的最后一個鉤子函數(shù),數(shù)據(jù)掛載完畢真實dom元素也已經(jīng)渲染完成了,這個鉤子函數(shù)內(nèi)部可以做一些實例化相關(guān)的操作mounted(){// DOM已掛載完成可以操作DOM}作用虛擬DOM已掛載到真實DOM$el屬性可用組件已完全渲染應用場景exportdefault{mounted(){// 場景1操作DOM元素最常見this.initDOMOperations();// 場景2初始化第三方庫需要DOMthis.initThirdPartyLibraries();// 場景3添加事件監(jiān)聽器this.bindEventListeners();// 場景4執(zhí)行依賴DOM的異步操作this.performDOMDependentAsyncTasks();// 場景5測量DOM元素尺寸this.measureDOMElements();},methods:{initDOMOperations(){// 1. 聚焦輸入框if(this.$refs.searchInput){this.$refs.searchInput.focus();this.$refs.searchInput.select();}// 2. 設(shè)置滾動位置constsavedScrollsessionStorage.getItem(scrollPosition);if(savedScrollthis.$refs.scrollContainer){this.$refs.scrollContainer.scrollTopparseInt(savedScroll);}// 3. 動態(tài)修改樣式this.$el.classList.add(loaded);this.$refs.header.style.backgroundColorthis.themeColor;},initThirdPartyLibraries(){// 1. 初始化圖表庫ECharts/Chart.jsif(this.$refs.chart){this.chartInstanceecharts.init(this.$refs.chart);this.chartInstance.setOption(this.chartOptions);}// 2. 初始化地圖百度地圖/高德地圖if(this.$refs.mapContainer){this.mapnewAMap.Map(this.$refs.mapContainer,{zoom:12,center:[116.397428,39.90923]});}// 3. 初始化富文本編輯器if(this.$refs.editor){this.editornewEditor({el:this.$refs.editor,content:this.content});}// 4. 初始化代碼編輯器if(this.$refs.codeEditor){this.codeMirrorCodeMirror.fromTextArea(this.$refs.codeEditor,{mode:javascript,theme:material,lineNumbers:true});}},bindEventListeners(){// 1. 窗口大小變化監(jiān)聽window.addEventListener(resize,this.handleResize);// 2. 全局鍵盤事件document.addEventListener(keydown,this.handleGlobalKeydown);// 3. 滾動事件監(jiān)聽window.addEventListener(scroll,this.handleScroll,{passive:true});// 4. 鼠標事件this.$el.addEventListener(mouseenter,this.handleMouseEnter);this.$el.addEventListener(mouseleave,this.handleMouseLeave);},performDOMDependentAsyncTasks(){// 1. 延遲加載圖片this.$nextTick((){constlazyImagesthis.$el.querySelectorAll(img[data-src]);lazyImages.forEach(img{img.srcimg.dataset.src;});});// 2. 執(zhí)行動畫setTimeout((){this.$el.classList.add(animate-in);},100);},measureDOMElements(){// 1. 獲取元素尺寸if(this.$refs.container){constrectthis.$refs.container.getBoundingClientRect();this.containerWidthrect.width;this.containerHeightrect.height;}// 2. 計算響應式布局this.calculateResponsiveLayout();}},beforeDestroy(){// 必須清理// 1. 移除事件監(jiān)聽window.removeEventListener(resize,this.handleResize);document.removeEventListener(keydown,this.handleGlobalKeydown);// 2. 銷毀第三方庫實例if(this.chartInstance){this.chartInstance.dispose();}if(this.map){this.map.destroy();}if(this.editor){this.editor.destroy();}// 3. 清理定時器clearTimeout(this.animationTimer);}}3、更新階段1、beforeUpdate在數(shù)據(jù)發(fā)生改變后DOM 被更新之前被調(diào)用。這里適合在現(xiàn)有 DOM 將要被更新之前訪問它比如移除手動添加的事件監(jiān)聽器。解釋這個鉤子函數(shù)初始化的不會執(zhí)行,當組件掛載完畢的時候并且當數(shù)據(jù)改變的時候才會立馬執(zhí)行,這個鉤子函數(shù)獲取dom的內(nèi)容是更新之前的內(nèi)容beforeUpdate(){// 數(shù)據(jù)已變化DOM更新前}作用檢測到數(shù)據(jù)變化重新計算虛擬DOM但還未更新真實DOM應用場景exportdefault{data(){return{messages:[],scrollPosition:0};},beforeUpdate(){// ? 場景1保存DOM狀態(tài)如滾動位置if(this.$refs.messageList){this.scrollPositionthis.$refs.messageList.scrollTop;this.scrollHeightthis.$refs.messageList.scrollHeight;}// ? 場景2檢查數(shù)據(jù)變化類型if(this.messages.length!this.previousMessageCount){this.hasNewMessagestrue;}this.previousMessageCountthis.messages.length;// ? 場景3性能監(jiān)控if(this.$options.performanceLogging){console.time(dom-update);}// ? 場景4取消不必要的操作if(this.isScrolling){console.log(正在滾動延遲DOM更新);}// ? 不要在這里修改正在更新的數(shù)據(jù)// this.messages.push(新消息); // 會導致無限循環(huán)}}2、updated在數(shù)據(jù)更改導致的虛擬 DOM 重新渲染和更新完畢之后被調(diào)用。當這個鉤子被調(diào)用時組件 DOM 已經(jīng)更新所以你現(xiàn)在可以執(zhí)行依賴于 DOM 的操作。然而在大多數(shù)情況下你應該避免在此期間更改狀態(tài)。如果要相應狀態(tài)改變通常最好使用計算屬性或 watcher 取而代之。updated(){// DOM已更新完成}作用虛擬DOM的差異已應用到真實DOMDOM更新完成組件重新渲染完成應用場景exportdefault{updated(){// ? 場景1恢復DOM狀態(tài)如滾動位置if(this.$refs.messageListthis.hasNewMessages){// 保持滾動在底部聊天應用場景this.$refs.messageList.scrollTopthis.$refs.messageList.scrollHeight;this.hasNewMessagesfalse;}// ? 場景2更新第三方庫if(this.chartInstancethis.chartDataChanged){this.chartInstance.setOption({series:[{data:this.chartData}]});this.chartDataChangedfalse;}// ? 場景3執(zhí)行DOM更新后的操作this.performPostUpdateOperations();// ? 場景4觸發(fā)過渡動畫if(this.shouldAnimate){this.$nextTick((){this.$el.classList.add(update-complete);});}// ? 場景5性能日志if(this.$options.performanceLogging){console.timeEnd(dom-update);console.log(DOM更新完成耗時:${performance.now()-this.updateStartTime}ms);}// ? 重要警告避免在此修改響應式數(shù)據(jù)// 錯誤示例// if (this.count 10) {// this.count; // 會導致無限更新循環(huán)// }// ? 正確做法使用條件判斷 $nextTickif(this.shouldAutoIncrementthis.countthis.maxCount){this.$nextTick((){this.count;});}},methods:{performPostUpdateOperations(){// 1. 高亮新增項constnewItemsthis.$el.querySelectorAll(.item-new);newItems.forEach(item{item.classList.add(highlight);setTimeout((){item.classList.remove(item-new);},1000);});// 2. 更新工具提示位置if(this.tooltips){this.tooltips.forEach(tooltiptooltip.updatePosition());}// 3. 觸發(fā)自定義事件this.$emit(dom-updated,{timestamp:Date.now(),elementCount:this.$el.children.length});}}}4、銷毀階段作用核心清理資源防止內(nèi)存泄漏1、beforeDestroy實例銷毀之前調(diào)用。在這一步實例仍然完全可用。當組件銷毀的時候就會觸發(fā)這個鉤子函數(shù)代表銷毀之前可以做一些善后操作,可以清除一些初始化事件、定時器相關(guān)的東西。beforeDestroy(){// Vue 2beforeUnmount(){// Vue 3// 實例銷毀前實例仍然完全可用}作用實例即將銷毀但所有功能仍然可用最后的機會進行清理工作應用場景exportdefault{data(){return{resources:{timers:[],listeners:[],connections:[]}};},beforeDestroy(){// 資源清理清單// 1. 清理定時器this.resources.timers.forEach(timerId{clearInterval(timerId);clearTimeout(timerId);});// 2. 移除事件監(jiān)聽器this.resources.listeners.forEach(({target,event,handler}){target.removeEventListener(event,handler);});// 3. 關(guān)閉WebSocket/SSE連接if(this.websocketthis.websocket.readyStateWebSocket.OPEN){this.websocket.close(1000,組件銷毀);}if(this.eventSource){this.eventSource.close();}// 4. 取消HTTP請求if(this.currentRequest){this.currentRequest.cancel(組件銷毀請求已取消);}// 5. 清理第三方庫實例this.cleanupThirdPartyLibraries();// 6. 清理DOM引用this.$refs{};// 7. 移除全局狀態(tài)引用this.removeGlobalReferences();// 8. 保存狀態(tài)到本地存儲this.saveStateToStorage();// 9. 發(fā)送銷毀日志this.logDestruction();},methods:{cleanupThirdPartyLibraries(){// 清理各種第三方庫constlibraries[chartInstance,mapInstance,editorInstance,playerInstance,pdfViewer,codeMirror];libraries.forEach(libName{if(this[libName]typeofthis[libName].destroyfunction){this[libName].destroy();this[libName]null;}});},removeGlobalReferences(){// 從全局對象中移除引用if(window.activeComponents){constindexwindow.activeComponents.indexOf(this);if(index-1){window.activeComponents.splice(index,1);}}// 清除全局事件處理器deletewindow[${this._uid}_resize_handler];},saveStateToStorage(){// 保存需要持久化的狀態(tài)if(this.shouldPersistState){conststateToSave{formData:this.formData,filters:this.activeFilters,pagination:this.pagination};localStorage.setItem(component_state_${this.componentId},JSON.stringify(stateToSave));}},logDestruction(){// 發(fā)送銷毀統(tǒng)計navigator.sendBeacon(/api/component-lifecycle,JSON.stringify({component:this.$options.name,instanceId:this._uid,lifespan:Date.now()-this.createdAt,event:beforeDestroy}));}}}2、destroyed實例銷毀后調(diào)用。該鉤子被調(diào)用后對應 Vue 實例的所有指令都被解綁所有的事件監(jiān)聽器被移除所有的子實例也都被銷毀。Vue實例失去活性完全喪失功能destroyed(){// Vue 2unmounted(){// Vue 3// 實例已完全銷毀}作用實例已銷毀所有事件監(jiān)聽器已移除所有子實例已銷毀所有指令已解綁應用場景exportdefault{destroyed(){// ? 場景1最終清理確認console.assert(this.resources.timers.length0,還有未清理的定時器);console.assert(this.resources.listeners.length0,還有未清理的事件監(jiān)聽);// ? 場景2觸發(fā)父組件回調(diào)this.$emit(component-destroyed,{instanceId:this._uid,name:this.$options.name});// ? 場景3更新應用級狀態(tài)if(this.$root){this.$root.activeComponentCount--;}// ? 場景4性能分析記錄if(window.performanceMonitor){window.performanceMonitor.recordComponentLifecycle(this.$options.name,destroyed,performance.now()-this.createdAt);}// ? 此時不能訪問實例數(shù)據(jù)// console.log(this.message); // undefined 或報錯// ? 場景5內(nèi)存泄漏檢測輔助if(process.env.NODE_ENVdevelopment){// 在開發(fā)環(huán)境幫助檢測內(nèi)存泄漏console.log(組件${this.$options.name}已銷毀檢查是否有內(nèi)存泄漏);}},created(){// 記錄創(chuàng)建時間用于計算生命周期時長this.createdAtperformance.now();}}templatediv idappp idbox{{msg}}/pbutton clickchange更新/button/div/templatescriptexportdefault{data(){return{msg:hello}},methods:{change(){this.msghello world}},beforeCreate(){console.log(----------------beforeCreate)console.log(this.msg,document.getElementById(box))},created(){console.log(----------------created)console.log(this.msg,document.getElementById(box))},beforeMount(){console.log(----------------beforeMount)console.log(this.msg,document.getElementById(box))},mounted(){console.log(----------------mounted)console.log(this.msg,document.getElementById(box))},beforeUpdate(){console.log(----------------beforeUpdate)console.log(this.$el.innerHTML)console.log(this.msg,document.getElementById(box))},updated(){console.log(----------------updated)console.log(this.$el.innerHTML)console.log(this.msg,document.getElementById(box))}}/script當頁面初始化掛載完成之后當數(shù)據(jù)改變之后又會觸發(fā)beforeUpdateupdated兩個鉤子函數(shù)