
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链式调用来实现:
解决方案一:调整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项目后端数据已获取,前端页面却显示为空?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号