vue开发过程中遇到的坑

从课程列表页进入课程详情页, 再从课程详情页进入推荐的课程详情页(当前路由)时报错

报错详情:

解决方法:
在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);
  },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值