vue keep-alive保留组件活性 activated/deactivated 保存选择的子组件

keep-alive

文档 搜索 keep-alive
keep-alive是Vue内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。不会被销毁重新创建
如果router-view直接被包裹在keep-alive里面,所有路径匹配的视图组件都会被缓存

属性

include 字符串或者正则,只有匹配的组件会被缓存
exclude 字符串或者正则,只有匹配的组件不会被缓存
max  数字。最多可以缓存多少组件实例。
简单使用
<keep-alive>
	<router-view/>
</keep-alive>
include/exclude字符串或者正则,只有匹配的组件会/不会被缓存
// about 对应组件的 name  
// export default {
//   name:'about',
//   data(){return { }}
// }

// <keep-alive exclude="about">
// 多个 exclude="about,user" :exclude="['about','user']" :exclude="/about|user/" 
<keep-alive include ="about">  
	<router-view/>
</keep-alive>

关联方法 activated deactivated

必须在 被keep-alive包裹的组件才能触发 即该组件保留了状态

{
	created(){},
	activated(){ // 激活
    
  	},
  	deactiveated(){ // 组件丢失活性
	
	}
}

保存子组件选择不变化

在这里插入图片描述
即离开home组件后 回来还是展示消息组件

home.vue

<template>
  <div>
     home组件
     <br>
     <br>
     <router-link to="/home/news" tag="button" >新闻</router-link>
     <router-link to="/home/msg" tag="button" >消息</router-link>
   
     <router-view/>
  </div>
</template>

<script>
export default {
  data(){
    return {
      path:'/home/news'
    }
  },
  created(){
    this.$router.push(this.path)
  },
  activated(){ // 激活
    console.log('activated',this.path)
    this.$router.push(this.path)  // 跳转到保存的子路由路径
  },
  beforeRouteLeave(to,form,next){
    this.path = form.path // 保存离开前的子路由路径
    console.log('beforeRouteLeave',form) 
    next()
  }

}
</script>

<style></style>

路由配置

{
    path: '/home',
    name: 'home',
    component: () => import('@/components/Home'),
    meta:{title:"home"},
    children: [
        // {
        //     path: "/",
        //     redirect: 'news'  // 重定向 默认显示  
        // },
        {
            path: 'news', // 子路由不需要加 /
            name: 'news',
            meta:{title:"news"},
            component: () => import('@/components/home/News'),
        },
        {
            path: 'msg', 
            name: 'msg',
            meta:{title:"msg"},
            component: () => import('@/components/home/Msg'),
        }
    ]
},

app.vue

<router-link to="/home" tag="button" >home</router-link>
<router-link to="/about" tag="button" >关于</router-link>

<keep-alive>
   <router-view/>
</keep-alive>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值