vue使用keep-alive后清除緩存的方法
什么是keepalive?
在平常開發(fā)中,有部分組件沒有必要多次初始化,這時,我們需要將組件進行持久化,使組件的狀態(tài)維持不變,在下一次展示時,也不會進行重新初始化組件。
也就是說,keepalive 是 Vue 內置的一個組件,可以使被包含的組件保留狀態(tài),或避免重新渲染 。也就是所謂的組件緩存
基本用法
<keep-alive> <component /> //你的組件 </keep-alive>
需求:從列表頁進入詳情頁,再返回列表頁時保留查詢條件,但在切換其他tab時,清空查詢條件。
解決:保留查詢條件很簡單,直接引入keep-alive,但是清除的話,vue本身沒有api直接清除,所以要單獨處理。
參考文章:http://aspedrom.com/5HD5
router/index,攔截路由并做處理:
beforeRouteLeave:function(to, from, next){ // 增加離開路由時清除keep-alive if (from && from.meta.rank && to.meta.rank && from.meta.rank == to.meta.rank) {//此處判斷是如果返回上一層,你可以根據(jù)自己的業(yè)務更改此處的判斷邏輯,酌情決定是否摧毀本層緩存。 if (this.$vnode && this.$vnode.data.keepAlive) { if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache) { if (this.$vnode.componentOptions) { var key = this.$vnode.key == null ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '') : this.$vnode.key; var cache = this.$vnode.parent.componentInstance.cache; var keys = this.$vnode.parent.componentInstance.keys; if (cache[key]) { if (keys.length) { var index = keys.indexOf(key); if (index > -1) { keys.splice(index, 1); } } delete cache[key]; } } } } this.$destroy(); } next(); },
同時在路由中添加meta:
{ // 賬號列表 path: '/account', name: 'account', component: () => import('../views/account/index.vue'), meta: { title: '賬號列表' ,rank:1.5} }, { // 添加賬號 path: '/accountadd', name: 'accountadd', component: () => import('../views/account/add.vue'), meta: { title: '添加賬號' ,rank:2.5} }, { // 編輯賬號 path: '/accountedit/:id', name: 'accountedit', component: () => import('../views/account/add.vue'), meta: { title: '編輯賬號' ,rank:2.5} }, { // 角色列表 path: '/role', name: 'role', component: () => import('../views/role/index.vue'), meta: { title: '角色列表' ,rank:1.5} },
總結
到此這篇關于vue使用keep-alive后清除緩存的文章就介紹到這了,更多相關keep-alive清除緩存內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
element?el-tooltip實現(xiàn)自定義修改樣式
本文主要介紹了element?el-tooltip實現(xiàn)自定義修改樣式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07vue3導入excel并解析excel數(shù)據(jù)渲染到表格中(純前端實現(xiàn))
在Vue中實現(xiàn)導出Excel有多種方式,可以通過前端實現(xiàn),也可以通過前后端配合實現(xiàn),下面這篇文章主要給大家介紹了關于vue3導入excel并解析excel數(shù)據(jù)渲染到表格中的相關資料,文中介紹的方法是純前端實現(xiàn),需要的朋友可以參考下2024-04-04Vue組件間的通信pubsub-js實現(xiàn)步驟解析
這篇文章主要介紹了Vue組件間的通信pubsub-js實現(xiàn)原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-03-03