一、页面返回后不刷新

        1.在路由(router/index.js)中,对不刷新的页面设置:
meta: { keepAlive: true //true为需要缓存,false为不需要缓存(不需要的也可以不加) },
        2.在app.vue中设置:
<div id="app"> <keep-alive> <router-view
v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view
v-if="!$route.meta.keepAlive"></router-view> </div>
这时返回就不会触发created和mounted

二、记录滚动条位置,并在页面显示时设置它:

        1.在data中定义
scrollTop: 0,
        2.挂载:
//离开路由之前执行的函数,可用于页面的反向传值,页面跳转。 beforeRouteLeave(to, from, next) {
console.log("1212-beforeRouteLeave") // 记录滚动条位置 this.scrollTop =
document.documentElement.getElementsByClassName("itemBoxs")[0].scrollTop || 0;
//组件写法 this.scrollTop =
document.documentElement.getElementById('app').scrollTop || 0; //全局写法
console.log("this.scrollTop", this.scrollTop) next() }, // 组件激活时触发 activated()
{ // 还原滚动条位置 console.log("1212-activated")
document.getElementsByClassName("itemBoxs")[0].scrollTop = this.scrollTop || 0;
//组件写法 document.getElementById('app').scrollTop = this.scrollTop || 0; //全局写法 },
以上就实现了返回页面后滚动条记忆的功能啦!

如果想实现分情况决定是否记忆滚动条以及刷新组件数据,请继续往下看:

在上述keep-alive的基础上

1.定义全局变量(不要在data中定义!!!)

var isRefresh = false; //定义是否需要刷新

注: 之所以在定义全局变量isRefresh而不在data里定义是因为当生命周期进入beforeRouteEnter的时候,此时当前页面还没有被mounted,因此我们是获取不到当前实例this的指向的,变量值也取不到。

2.定义beforeRouteEnter
//路由进入前判断是否重新加载还是缓存 beforeRouteEnter(to, from, next){ if(from.name ==
'textbookModeSelection'){ //哪个页面 进入需要刷新 isRefresh = true; //需要刷新 }else{
isRefresh = false; } next() },

3.定义activated
// 组件激活时触发 activated() { if(isRefresh) { //刷新 this.chooseCourseIndex = null;
//清空需要的数据 document.getElementsByClassName("itemBoxs")[0].scrollTop = 0; //置顶滚动条
this.init(); //调用获取数据方法 }else{ //不刷新 还原滚动条位置
document.getElementsByClassName("itemBoxs")[0].scrollTop = this.scrollTop || 0;
}
注: 
keep-alive之后不会执行created,mounted钩子了,在activated中判断需要刷新之后,将列表数据初始化,发起请求即可,不刷新时则返回到列表记录的滚动条的位置

4.定义beforeRouteLeave
//路由离开前执行 beforeRouteLeave(to, from, next) { // 记录滚动条位置 this.scrollTop =
document.documentElement.getElementsByClassName("itemBoxs")[0].scrollTop || 0;
next() },

完成!

技术
今日推荐
PPT
阅读数 131
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信