vue keep-alive请求数据的方法示例
2018-05-16 09:20
901 查看
背景
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);
不知道有咩有帮大家理清思路,有问题可以留言,以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- vue.js实现请求数据的方法示例
- 改变vue请求过来的数据中的某一项值的方法
- vue使用keep-alive实现数据缓存不刷新
- vue 使某个组件不被 keep-alive 缓存的方法
- vue解决使用webpack打包后keep-alive不生效的方法
- Pull解析xml文件,并用HttpUtils请求数据接口(示例方法)
- vue项目优化之通过keep-alive数据缓存的方法
- vue开发请求本地模拟数据的配置方法
- vue中进入详情页记住滚动位置的方法(keep-alive)
- 通过vue提供的keep-alive减少对服务器的请求次数
- 改变vue请求过来的数据中的某一项值的方法(详解)
- Vue-cli 使用json server在本地模拟请求数据的示例代码
- Python实现向服务器请求压缩数据及解压缩数据的方法示例
- vue中各组件之间传递数据的方法示例
- vue配置请求本地json数据的方法
- vue keep-alive 数据更新问题
- vue2.0 keep-alive 缓存页面数据 3ff0
- vue axios数据请求及vue中使用axios的方法
- webpack+vuex+axios 跨域请求数据的示例代码
- (vue.js)vue 父组件使用keep-alive和infinite-scroll导致在子组件触发父组件的infinite-scroll方法