首页 > 解决方案 > 通过 URL 或 F5 调用时,Vue.js 组件不加载/渲染数据

问题描述

我有一个 Vue.js SPA,其中一些页面显示来自后端的数据。当我通过导航栏导航页面时,一切正常,组件和数据已加载。

当我在页面上时,例如localhost:8080/#/mypage并按 F5,数据不会被加载/呈现。当我通过地址栏直接导航到页面时也是如此。

数据在此函数中加载:

async beforeMount() {
    await this.initializeData();
}

我试图在每个生命周期钩子中调用该方法,即创建、beforeCreated、安装等...

在挂载的生命周期钩子中,我将布尔属性设置为 true,以便仅在加载组件时呈现表格(使用 v-if 完成)。

mounted() {
    this.componentLoaded = true;
}

不确定这是否重要,但我已经尝试过或不使用它,但它不起作用。

如果有人知道这里发生了什么,我将不胜感激。

编辑:

this.applications 是一个道具,包含多个包含实例的应用程序。我想从后端添加一些变量到每个应用程序。

initializeData: function () {
      let warn = 0;
      console.log("1");

      this.applications.forEach(async application => {
        const instance = application.instances[0];

        console.log("2");

        let myData = null;

        try {
          const response = await instance.axios.get('url/myData');
          myData = response.data;
        } catch (err) {
        }

        let tmpCount = 0;   
        let tmpFulfilled = 0;

        myData.forEach(ba => {
            if(!ba.fulfilled){
              warn++;
              application.baAllFulfilled = false;
            }else {
              tmpFulfilled++;
            }
            tmpCount++;
          })

        console.log("3");

        // Assign values
        this.baTotalWarnings = warn;
        application.baAnzahl = tmpCount;
        application.baFulfilled = tmpFulfilled;

        this.componentLoaded = true;
      }

标签: vue.js

解决方案


尝试从 beforeMount 中删除 async 和 await 关键字,并从 mount 中删除 this.componentLoaded。而是在您的 initializeData 方法的 then 块中(或在 await 之后)设置它。我不确定 Vue 在其生命周期方法中是否支持 async 关键字。

像这样的东西:

beforeMount() {
    this.initializeData(); // start processing the method
}

methods: {
    initializeData() {
        callToBackend().then(() => {
            this.componentLoaded = true // backend call ready, can now show the table
        })
    }
}

推荐阅读