我的项目是一进首页产品列表的路由就调取数据,所以当每次用户点进详情页的时候,再返回到原来页面,数据就会刷新一次,就没有停留到用户原来浏览的位置,用户体验很不好。
1、在App.vue中,判断哪些页面是需要缓存的,哪些页面是不需要缓存的
<template>
<div id="app">
<keep-alive >
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>
2、在router的index.vue中,在需要缓存的页面的路由中,加上 keepAlive:true,然后用 scrollBehavior记录位置
const routes = [
{
path: '/',
component: Layout,
children:[
{
path: '/', // 首页
name: 'Home',
component: () => import('../views/Home.vue'),
meta: {
requireAuth: true, // 添加该字段,表示该路由需要登录才能访问
keepAlive:true,//需要缓存的页面
}
},
{
path: '/product', // 产品详情
name: 'product',
component: () => import('../views/product/index.vue'),
meta: {
requireAuth: true // 添加该字段,表示该路由需要登录才能访问
}
},
]
}
],
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
//记录缓存的位置
scrollBehavior(to,from,savePosition){
if(savePosition){
return savePosition
}else{
return{x:0,y:0}
}
},
})
3、在产品详情页中加 beforeRouteLeave
然后就可以实现用户点进产品详情页的时候,再返回产品列表页面,还停留在用户上一次点击的位置,这样就不会用户返回,回到顶部了且数据进行了刷新。