我们从零开始用vue搭建了外卖项目,对vue也有了更进一步的了解,我们从点菜,评价,商家三个模块逐步实现,我们来回顾一下以往模块:
模块回顾
点菜模块:
评价模块:
商家模块:
模块优化
我们现在需要更进一步完善我们的项目,现在有一个这样的需求:
当我们在点菜栏目下选择了对应产品,然后又浏览其他项目,此时如果我们返回点菜栏目下,那么对应商品还是依然会存在的。这个需求在技术上实现就需要用到vue的keep-alive。
现在我们在app.vue中加入keep-alive:
<template> <div id="app"> <myHeader :poiInfo="poiInfo"></myHeader> <myNav :commentNum="commentNum"></myNav> <keep-alive> <router-view/> </keep-alive> </div></template><script>import myHeader from "components/Header/Header";import myNav from "components/Nav/Nav";export default { name: "App", components: { myHeader, myNav }, data() { return { poiInfo: {}, commentNum: 0 }; }, created() { this.$axios .get("api/goods") .then(response => { let json = response.data; if (json.code === 0) { this.poiInfo = json.data.poi_info; } }) .catch(function(error) { // handle error console.log(error); }); // 评价 this.$axios .get("/api/rates") .then(response => { let json = response.data; if (json.code === 0) { this.commentNum = json.data.comment_num; } }) .catch(function(error) { // handle error console.log(error); }); }};</script><style>#app {}</style>
我们使用<keep-alive>标签包裹<router-view/>也就是以上我们编写的三个模块。这样能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。从而满足了我们项目需求,也提高了应用的性能。
总结
本篇我们做了项目最后的优化。整个vue专题就圆满结束了,感谢同学们的陪伴,相信这个专题能够真正地帮到大家。也特别希望大家能够持续关注后续的文章,大彬哥陪伴大家一起涨薪,一起突破自我。