这次给大家带来怎样使用vue keep-alive请求数据,使用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
const appRouter = {
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);
export default new Router(appRouter);相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
如何操作vue input输入校验字母数字组合且长度小于30
以上就是怎样使用vue keep-alive请求数据的详细内容,更多请关注php中文网其它相关文章!
Keep是一款健身安排,无论是想减肥塑形或增肌,还是寻找健身跑步瑜伽计步等训练计划,你可以随时随地选择课程进行训练!权威教练视频教学,健身干货自由分享!有需要的小伙伴快来保存下载体验吧!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号