
Vue项目后端数据获取成功,但前端页面显示为空白?这是一个常见的Vue.js开发问题。本文将分析一个实际案例,并提供解决方案。
案例中,appgoods组件尝试从/goods/list接口获取商品数据,并渲染到页面。代码使用$axios进行网络请求,将数据赋值给tableData,然后通过getNew方法进行排序和筛选,最终使用newgoods渲染页面。尽管控制台显示数据已获取,页面仍为空白。
问题代码:
import MyPanel from "@/components/Shop/MyPanel";import AppMore from "@/components/Shop/AppMore";import Mylist from "@/components/Shop/Mylist";export default { name: "AppGoods", components: {Mylist, AppMore, MyPanel}, data(){ return{ tableData:[], allnewgoods:[], newgoods: [], } }, methods:{ getNew(){ console.log(this.tableData); this.allnewgoods = this.tableData.sort( function sortData(a, b){ return new Date(b.ctime).getTime() - new Date(a.ctime).getTime() }); this.newgoods=this.allnewgoods.slice(0,4) }, loadGet() { this.$axios.get(this.$httpUrl+'/goods/list').then(res=>res.data).then(res=>{ console.log(res); if(res.code == 200){ this.tableData=res.data console.log(this.tableData); }else{ alert("获取数据失败"); } }) } }, created() { this.getNew(); // 此处调用过早 this.loadGet(); }}
问题根源在于getNew方法在loadGet方法之前执行。由于$axios.get是异步操作,this.tableData在getNew执行时为空,导致newgoods也为空,页面显示空白。
立即学习“前端免费学习笔记(深入)”;
解决方案:确保getNew方法在tableData赋值后执行。 可以通过调整created钩子函数中的代码顺序,或者利用then链式调用来实现:
Ideogram
Ideogram是一个全新的文本转图像AI绘画生成平台,擅长于生成带有文本的图像,如LOGO上的字母、数字等。
512 查看详情
解决方案一:调整created钩子函数代码顺序
created() { this.loadGet();}
在loadGet方法的then回调中调用getNew:
loadGet() { this.$axios.get(this.$httpUrl+'/goods/list').then(res=>res.data).then(res=>{ console.log(res); if(res.code == 200){ this.tableData=res.data; this.getNew(); // 将getNew()调用移至此处 console.log(this.tableData); }else{ alert("获取数据失败"); } })}
解决方案二:使用then链式调用
loadGet() { this.$axios.get(this.$httpUrl+'/goods/list').then(res => res.data) .then(res => { if (res.code === 200) { this.tableData = res.data; this.getNew(); console.log(this.tableData); } else { alert("获取数据失败"); } });}
通过以上两种方法,可以确保getNew方法在数据获取完成后执行,从而解决页面显示为空白的问题。 建议选择解决方案二,代码更简洁易读。 记住,处理异步操作是前端开发中的关键。
以上就是Vue项目后端数据已获取,前端页面却显示为空?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/776639.html
微信扫一扫
支付宝扫一扫