方法一:
首先在定义路由的时候配置 meta 字段,自定义一个KeepAlive字段作为该页面是否缓存的标记:
router.js
const router= new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [{
path: '/',
name: 'home',
component: Home,
meta:{
keepAlive: true // 是否缓存组件
},
redirect: {
name: 'Login'
}
},
{
path: '/HomePage', // 首页面
name: 'HomePage',
component: () => import('./views/HomePage.vue'),
meta: {
keepAlive: true
},
{
path: 'onlineQuery',
name: 'onlineDatails',
component: () => import('./views/Datails/onlineDatails.vue'),
meta: {
keepAlive: true
}
}
,{
path: '/Login', // 登录
name: 'Login',
component: () => import('./views/Login.vue'),
meta: {
keepAlive: false
}
},
{
path: '*', // 未匹配到路由时重定向
redirect: '/',
meta: {
// requiresAuth: true,
// keepAlive: true
}
}
]
})
App.vue:
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" />
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" />
</div>
方法二:
使用<keep-alive>提供的 exclude 或者 include 选项,此处我们使用 exclude ,在App.vue中:
<div id="app">
<keep-alive exclude="detail">
<router-view />
</keep-alive>
</div>
需要注意的是,一定要给页面组件加上相应的name,例如在detail.vue中:
<script>
export default {
name: 'detail', // 这个name要和keep-alive中的exclude选项值一致
...
}
</script>
这么写就代表了在项目中除了name为detail的页面组件外,其余页面都将进行缓存。
转载:https://blog.csdn.net/asteriaV/article/details/101620684
查看评论