标签导航:

vue项目后端数据已获取,前端页面却显示为空?

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方法在数据获取完成后执行,从而解决页面显示为空白的问题。 建议选择解决方案二,代码更简洁易读。 记住,处理异步操作是前端开发中的关键。