vue keep-alive请求数据的方法示例
背景
index页面:首页品牌入口
list页面:商品列表页面
product页面:商品详情页面
从index页面进入list的时候要刷新页面,从product页面返回list的时候不需要刷新页面,所以list使用了keep-alive的属性,keepAlive设置为true,但是开发过程中发现一个问题,从product返回到list的时候,列表页面不是正确的品牌列表,而是之前一次点击的品牌列表。由于每个人遇到关于keep-alive请求数据不正确的问题不同,这里就直接说我的解决办法。希望能给大家一个思路。
解决办法
很多人都会通过修改keepAlive来改变keep-alive,我尝试后还是不行,就换了个思路
钩子函数的执行顺序
不使用keep-alive
beforeRouteEnter-->created-->mounted-->destroyed
使用keep-alive
beforeRouteEnter-->created-->mounted-->activated-->deactivated
先扫盲,多少人和我都不知道上面的知识,在keep-alive的页面中,可以在activated获取this.$route.params的参数
避开了设置keepAlive导致product返回的时候数据不对,当页面进入list的时候都是缓存状态,然后再通过是不是由index进入来判断是否执行activated里的函数,
list.vue
beforeRouteEnter(to,from,next){
//判断从index页面进入,将list的isBack设置为true
//这样就可以请求数据了
if(from.name=='index'){
to.meta.isBack=true;
}
next();
},
activated:function(){
if(this.$route.meta.isBack||this.isFirstEnter){
//清理已有商品列表的数据,重新请求数据,如果不清除的话就会有之前的商品缓存,延迟显示最新的商品
this.proData=[];
//请求数据
this.fetchData();
}
//重新设置当前路由的isBack
this.$route.meta.isBack=false;
//重新设置是否第一次进入
this.isFirstEnter=false;
},
mounted:function(){
//如果是第一次进入,或者刷新操作的话,也请求数据
this.isFirstEnter=true;
},
router.js
constappRouter={
mode:"history",
base:"/m/",
routes:[
{
path:"",
redirect:"/index"
},
{
path:"/index",
name:"index",
component:Index,
meta:{
keepAlive:true
}
},
{
path:"/list",
name:"list",
component:List,
meta:{
keepAlive:true,
isBack:false//isback是true的时候请求数据,或者第一次进入的时候请求数据
}
},
{
path:"/product/:id",
name:"product",
component:Product,
meta:{
keepAlive:false
}
}
]
};
Vue.use(Router);
exportdefaultnewRouter(appRouter);
不知道有咩有帮大家理清思路,有问题可以留言,以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。