這篇文章主要介紹了vue中activated的用法,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下
1、keep-alive
<keep-alive>包裹動態組件的時候,會緩存不活動的組件實例,而不是摧毀他們。其是一個抽象的組件,自身不會渲染一個DOM元素,也不會出現在父組件鏈中。
說白了被<keep-alive>包裹的組件其會被緩存
廢話不多說直接上例子.
我們現在創建兩個子組件conpoment1,compoment2,其內容如下
<template> <div class="wrapper"> <ul class="content"></ul> <button class="add" id="add" @click="add">添加子元素</button> </div> </template> <script> export default { data() { return {}; }, methods: { add() { let ul = document.getElementsByClassName("content")[0]; let li = document.createElement("li"); li.innerHTML = "我是添加的元素"; ul.appendChild(li); } } }; </script> <style > </style>
代碼不用解釋了吧,就是點擊按鈕在ul動態添加一個li元素。
接着我們在路由中注冊一下,再回到APP.vue中修改一下配置
<template> <div id="app"> <keep-alive> <router-view /> </keep-alive> </template>
這樣我們就會發現,當我們切換路由的時候,我們之前添加的子元素還回保存在那里
如果是這樣的話所有的頁面都被緩存了,一些需要重新加載不需要緩存的我們可以通過v-for來實現。當然我們可以在路由中設置一個key值來判斷組件是否需要緩存,就像下面這樣
//index.js { path: '/1', name: 'components1', component: Components1, meta: { keepAlive: true //判斷是否緩存 } }, { path: '/2', name: 'components2', component: Components2, meta: { keepAlive: false } },
然后我們的App.vue中只需要判斷其keepAlive值即可
<div id="app"> <keep-alive> <router-view v-if="$route.meta.keepAlive" /> </keep-alive> <router-view v-if="!$route.meta.keepAlive" /> </template>
這時候我們回到頁面中添加子元素並切換路由就會發現只有components1中的組件有緩存。
2、activated
先說下這個生命周期鈎子,官網說其是在服務器端渲染期間不被調用,
說白了其就是在掛載后和更新前被調用的。但如果該組件中沒有使用緩存,也就是沒有被<keep-alive>包裹的話,activated是不起作用的。我們直接來試一下就知道了。
//components1中 created() { console.log("1激活created鈎子函數"); }, activated() { console.log("1激活activated鈎子函數"); }, mounted() { console.log("1激活mounted鈎子函數"); } //components2中 created() { console.log("2激活created鈎子函數"); }, activated() { console.log("2激活activated鈎子函數"); }, mounted() { console.log("2激活mounted鈎子函數"); }
我們在2個組件中分別打印出其鈎子函數執行情況。我們可以看到
在執行components1時候其是執行了activated鈎子函數的,而components2則沒有,因為components2並沒有被<keep-alive>包裹,所以其並不會激活該鈎子函數。
當我們再切換一次路由的時候又發現了神奇的地方
組件1中只執行activated鈎子鈎子函數,而組件2則把創建和掛載的鈎子函數都執行了。
這就是緩存的原因,components其對組件進行了緩存所以並不會再一次執行創建和掛載。
簡單的說activated()函數就是一個頁面激活后的鈎子函數,一進入頁面就觸發;
所以當我們運用了組件緩存時,如果想每次切換都發送一次請求的話,需要把請求函數寫在activated中,而寫在created或mounted中其只會在首次加載該組件的時候起作用。
3、補充:
keep-alive組件除了actived,還有deactived函數鈎子
activated
類型:func
觸發時機:keep-alive組件激活時使用
deactivated
類型:func
觸發時機:keep-alive組件停用時調用