vue.js中created()與activated()的個人使用解讀
vue.js中created()與activated()的使用
created()
在創(chuàng)建vue對象時,當html渲染之前就觸發(fā);
但是注意,全局vue.js不強制刷新或者重啟時只創(chuàng)建一次,也就是說,created()只會觸發(fā)一次;
activated()
在vue對象存活的情況下,進入當前存在activated()函數(shù)的頁面時,一進入頁面就觸發(fā);可用于初始化頁面數(shù)據(jù)等
vue.js中created()、activated()、deactivated()理解
created()
在創(chuàng)建vue對象時,當html渲染之前觸發(fā);但是注意,全局vue.js不強制刷新或者重啟時只創(chuàng)建一次,也就是說,created()只會觸發(fā)一次;
activated()
在vue對象存活的情況下,進入當前存在activated()函數(shù)的頁面時,一進入頁面就觸發(fā);可用于初始化頁面數(shù)據(jù)、keepalive緩存組件后,可執(zhí)行方法;
deactivated()
離開組件時執(zhí)行;
注意:activated()和deactivated()只有在<keep-alive></keep-alive>包裹的時候才有效;
例:
新建兩個組件,compA,compB:
<template> <div class="app"> ? ? 我是組件A </div> </template>
<script> ? ? export default{ ? ? ? ? name: "compA", ? ? ? ? data(){ ? ? ? ? ? ? return { ? ? ? ? ? ? } ? ? ? ? }, ? ? ? ? created(){ ? ? ? ? ? ? console.log('created'); ? ? ? ? }, ? ? ? ? activated(){ ? ? ? ? ? ? console.log('activated'); ? ? ? ? }, ? ? ? ? deactivated(){ ? ? ? ? ? ? console.log('deactivated'); ? ? ? ? } ? ? } </script>
同理建compB;
在view中引用兩個組件:
<template> <div class="app"> ? ? <div class="bth"> ? ? ? ? <button @click="currentComponent='compA'">A</button> ? ? ? ? <button @click="currentComponent='compB'">B</button> ? ? ? ? </div> </div> <keep-alive> ? ? <component :is="currentComponent"></component> </keep-alive> </template>
<script> ? ? import compA from './component/compA' ? ? import compB from './component/compB' ? ? export default{ ? ? ? ? name: "App", ? ? ? ? component: { ? ? ? ? ? ? compA, compB ? ? ? ? }, ? ? ? ? data(){ ? ? ? ? ? ? return { ? ? ? ? ? ? ? ? currentComponent: 'compA' ? ? ? ? ? ? } ? ? ? ? } ? ? } </script>
在點擊切換B組件時,A組件的deactivated()會執(zhí)行;
注::is后綁定組件名,渲染當前組件;
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
從Echarts報錯中學(xué)習(xí)Vue3?ref和shallowRef區(qū)別及其組件二次封裝demo
這篇文章主要介紹了從Echarts報錯中學(xué)習(xí)Vue3?ref和shallowRef區(qū)別及其組件二次封裝demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11Vue文件的組織結(jié)構(gòu)不合理之優(yōu)化項目結(jié)構(gòu)詳解
在這篇博客中,我們將探討 Vue 文件組織結(jié)構(gòu)不合理的幾個常見問題,并提供解決方案,以幫助開發(fā)者創(chuàng)建更清晰、更高效的項目文件結(jié)構(gòu),希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03el-descriptions引入代碼中l(wèi)abel不生效問題及解決
這篇文章主要介紹了el-descriptions引入代碼中l(wèi)abel不生效問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12