一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

vue中进入详情页记住滚动位置的方法(keep-alive)

时间:2018-09-26 编辑:猪哥 来源:一聚教程网

> 有时业务提出这样一个需求 就是从商品页面进入到列表详情页 要保存当前滚动的位置,这里我就想到了keep-alive

1.首先在路由中引入需要的模块

{ 
path: ‘/scrollDemo', 
name: ‘scrollDemo', 
meta: { 
keepAlive: true // 需要缓存 
}, 
component: resolve => { require([‘../view/scrollDemo.vue'], resolve) } 
}

2.在App.vue中设置缓存组件

    // 缓存组件跳转的页面
    
   

 // 非缓存组件跳转页面
 

3.在页面注册对应的事件

1. 在return中定义一个初始值 scroll

2. 在mouted中 ,mouted中的方法代表dom已经加载完毕

window.addEventListener('scroll', this.handleScroll);

3.methods 用于存放页面函数

   handleScroll () {
    this.scroll = document.documentElement && document.documentElement.scrollTop

    console.log(this.scroll)
   }

4. activated 为keep-alive加载时调用

   activated() {
     if(this.scroll > 0){
      window.scrollTo(0, this.scroll);
      this.scroll = 0;
      window.addEventListener('scroll', this.handleScroll);
     }
  }

5.deactivated 页面退出时关闭事件 防止其他页面出现问题

  deactivated(){
   window.removeEventListener('scroll', this.handleScroll);
  }

热门栏目