在router.js里面
const router = new VueRouter({
mode: 'history',
routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
if (from.meta.keepAlive) {
from.meta.savedPosition = document.body.scrollTop
}
return { x: 0, y: to.meta.savedPosition || 0 }
}
}
})
在router.js里面需要记录位置的单页面里面
let routes = [
{
path: '/',
name: 'home',
component: home,
meta: {
keepAlive: true
}
}
App.vue里面
这样写的意义就是不缓存所有页面,哪个地方写了 keepAlive:true,哪个地方就记录位置(加缓存)
<keep-alive >
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
位置确实记录上了(加缓存,返回不刷新页面),也就是说,返回不触发created,所以有些页面需要返回触发的东西都写在activated里面。
<keep-alive >
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>