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>