在我们切换组件的时候,组件内的值会消失,但是我们又想保存组件内原有的值,这个时候就可以使用keepAlive
1.按需加载router-view
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
2 在路由中选择需要缓存的组件
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
meta: {
keepAlive: true
}
}
]
3.被缓存的组件有两个钩子函数
activated () {
console.log('进')
},
deactivated () {
console.log('出')
},