从课程列表页进入课程详情页, 再从课程详情页进入推荐的课程详情页(当前路由)时报错
报错详情:
解决方法:
在router.js 中加入下面的代码
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error=> error)
}
组件中:
this.$router.push({path:`/classDetail/${code}`}) // 进入当前路由, 有历史记录
window.scrollTo(0,0) // 滚动到顶部
App.vue里有tab组件(只有首页和我的页面显示), 当加载其他组件时,隐藏
App.vue:
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" id="a"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" id="b" />
<Tab v-if="showTab" />
</div>
App.js:
watch:{
$route(e){
console.log(e)
if(e.name == 'Index' ||e.name=='Self' ){
this.showTab = true;
}else{
this.showTab = false
}
}
}
从列表页进入详情页, 再返回列表页回到之前的滚动位置
需要使用keep-alive缓存数据
router.js :
export default new Router({
routes: [
{
path: '/',
name: 'Index',
meta: {
keepAlive: true // 需要缓存
},
component: Index
},
{
path: '/classdetail/:id',
name: 'Detail',
meta: {
keepAlive: false // 需要缓存
},
component: Detail
},
})
App.vue:
<div id="app">
<keep-alive>
<router-view v-if="$route.meta.keepAlive" id="a"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive" id="b" />
<Tab v-if="showTab" />
</div>
Index.vue: // 需要缓存的组件
beforeRouteLeave(to, from, next){
console.log('离开时的滚动高度'+this.scroll)
storage.setStorage('scroll',this.scroll)
next()
},
activated() {
this.scroll = storage.getStorage('scroll')
if(this.scroll > 0){
// 定时器一定要加
setTimeout(() => {
window.scrollTo(0, this.scroll);
this.scroll = 0;
window.addEventListener('scroll', this.handleScroll);
},0)
}
},
deactivated(){
window.removeEventListener('scroll', this.handleScroll);
},