注意:keep-alive不会缓存滚动条的位置的
第一步,去router/index.js
路由对象/home, 上添加meta额外信息
Vue.use(VueRouter)
const routes = [
{
// 根路径 的 重定向
path: '/',
redirect: '/layout'// 重定向
}, {
// 首页
path: '/layout',
component: Layout,
redirect: '/layout/home',
children: [
{
// path: '', 或者 重定向
path: 'home',
component: Home,
meta: { //路由元信息
// 给路由对象添加额外的信息>>>>你要保存哪个组件窗口位置,就把meta加到哪个组件的路由里
scrollY: 0
}
}, {
path: 'user',
component: User
}
]
}
]
第二步,去要保存窗口位置的组件,我的是home组件,找到home组件,
注意是和method平齐
methods: {
},
// 路由离开前
beforeRouteLeave (to, from, next) {
// 可以访问组件实例 `this`
// console.log(to) 要去的路由对象
// console.log(from) 就是当前路由
// 把滚动的高度 保存到 路由对象的meta字段中的scrollY上
// console.log('home', window.scrollY)
// console.log(to, from)
from.meta.scrollY = window.scrollY
next()
},
created () {
// console.log(this.channelList)
// 页面切回来,自动滚动到 上次 保存的 滚动位置
// window.scrollTo(x, y)
// console.log('home回来了')
this.$nextTick(() => {
window.scrollTo(0, this.$route.meta.scrollY)
})
},