vue项目(缓存页面)保持页面状态,点击tag切换后,还能回到之前操作的样子

保持页面操作中状态,在点击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,include中字符串集合就是缓存的组件,通过组件的name去匹配。因此组件需要定义name,跟路由的name一致

<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,'
  }
//......其他代码
}

  

posted @ 2022-05-05 15:13  zwbsoft  阅读(666)  评论(0编辑  收藏  举报