index页面:首页品牌入口
list页面:商品列表页面
product页面:商品详情页面
从index页面进入list的时候要刷新页面,从product页面返回list的时候不须要刷新页面
因此list使用了keep-alive的属性,keepAlive设置为true,可是开发过程当中发现一个问题,
从product返回到list的时候,列表页面不是正确的品牌列表,而是以前一次点击的品牌列表。
因为每一个人遇到关于keep-alive请求数据不正确的问题不一样,这里就直接说个人解决办法。
但愿能给你们一个思路。vue
不少人都会经过修改keepAlive来改变keep-alive,我尝试后仍是不行,就换了个思路缓存
不使用keep-alive beforeRouteEnter --> created --> mounted --> destroyed 使用keep-alive beforeRouteEnter --> created --> mounted --> activated --> deactivated
先扫盲,多少人和我都不知道上面的知识,在keep-alive的页面中,能够在 activated获取this.$route.params的参数app
避开了设置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.jsfetch
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);
不知道有咩有帮你们理清思路,若是有什么疑问能够留言交流,(づ ̄3 ̄)づ╭❤~this