首页 > 解决方案 > 网页在 Axios GET 响应之前加载

问题描述

我对 Vue.js 很陌生。

可能有人可以帮助我解决下一个问题:

我的网页元素的值取自我应该在页面加载之前发送的 Axios GET 响应。但是我的页面在我得到服务器的响应之前就已经加载了。我收到一个错误,即值未定义。

我的 main.vue 文件

  beforeMount()
   {
      this.firstTimeRun();
   },

我的 mixin.js 文件

   methods: {
    async firstTimeRun() {
        await this.getConfig();
        await this.getAlarmStatus();
    },
    async getConfig() {
        const configResponce = await axios.get('http://10.10.10.10/multi_get.json?c0=config')
            .then((res => { this.config = res; }))
            .catch(err => console.log(err));
        this.$store.commit("setConfigData", this.config);
    },
    async getAlarmStatus() {
        const alarmResponce = await axios.get('http://10.10.10.10/multi_get.json?c0=alarm_status')
            .then((res => {
                this.alarm_status = res;
            }))
            .catch(err => console.log(err));
        this.$store.commit("setAlarmData", this.alarm_status);
    },

   // In this method I fill the elements and I suppose to use data from getConfig() and 
   getAlarmStatus() methods.

   fillElements(){
    // Do something...
    }
  }

有人对此有答案吗?谢谢。

标签: javascriptvuejs2promiseaxios

解决方案


当您调用 get 方法时,添加 e.preventDefault 方法。单击提交按钮时,它将停止页面加载。

async getConfig(e) {

e.preventDefault();
        const configResponce = await axios.get('http://10.10.10.10/multi_get.json?c0=config')
            .then((res => { this.config = res; }))
            .catch(err => console.log(err));
        this.$store.commit("setConfigData", this.config);
    },

推荐阅读