vue專案(快取頁面)保持頁面狀態,點選tag切換後,還能回到之前操作的樣子
阿新 • • 發佈:2022-05-05
保持頁面操作中狀態,在點選tag切換的時候,還能回到之前的樣子。拿收集整編頁面為例。
主要用到vue 內建元件keep-alive,參考文件:API — Vue.js (vuejs.org)
把需要keep-alive的路由(name)寫進狀態中,用狀態來控制快取頁面。
1、路由設定,給需要keep-alive的路由,在mate中設定keepAlive為‘1’
{ path:'/collectionmanage', name:'CollectionManage', component:resolve=>require(['@/元件所在路徑/collectionmanage’],resolve), meta:{ title:'收集整編', keepAlive:'1' } }
2、在整體佈局rooter-view外面包裹keep-alive
<keep-alive :include="$store.state.keepalive.substring(0,$store.state.keepalive.lastIndexOf(','))"> <rooter-view :key='key'> </keep-alive> watch:{ $route(to,from){ if(to.meta.keepAlive && to.meta.keepAlive == '1'){ //判斷路由中是否設定了keepAlive為1 if(to.query.tag==1){ //點選tag標籤時保持快取 if(this.$store.state.keepalive.indexOf(to.name)==-1){ this.$store.state.keepalive = this.$store.state.keepalive+to..name+',' } } }else{ //點選左側選單時,先去除快取,在需要快取的頁面裡再新增快取 if(this.$store.state.keepalive.indexOf(to.name)!==-1){ this.$store.state.keepalive = this.$store.state.keepalive.replace(to.name) } } } }
3、頁面元件內,當有初始操作的時候,判斷狀態內是否有該路由的name,如果沒有,寫入
比如進入收集整編頁面後,最先點選左側樹,那就在點選樹事件內增加以下程式碼
//點選左側樹 handleTreeNodeClick(data,node){ if(this.$store.state.keepalive.indexOf('CollectionManage')==-1){ this.$store.state.keepalive = this.$store.state.keepalive+'CollectionManage,' } //......其他程式碼 }