首页 > 解决方案 > 如何在这个 axios Vuejs 中获取变量

问题描述

嗨,我在 Vuejs 中有这段代码:

forceFileDownload(response, id) {
   axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken)
  .then(response => {
      this.documentation_data = response.data.data;
   });
   console.log(this.documentation_data);
   const url = window.URL.createObjectURL(new Blob([response.data]))
   const link = document.createElement('a')
   link.href = url
   link.setAttribute('download', 'movement.pdf')
   document.body.appendChild(link)
   link.click()
  },

我想从上面的 axios 中获取 this.documentation_data,我该怎么做呢?因为它说未定义..并且有数据。

谢谢!

标签: javascriptvue.jsaxios

解决方案


此后的代码console.log不会等待 axios 完成请求,因此它在分配之前执行。 this.documentation_data

您需要将所有代码移动到then块中,以使其行为符合您的预期。但是,如果这样做,则根本不需要将其分配给documentation_data变量,您还不如只使用局部变量。

forceFileDownload(response, id) {
   axios.get('/api/documentation/'+ id +'/edit?api_token='+App.apiToken)
    .then(response => {
        console.log(response.data.data); // P.S. Are you sure .data.data is correct here?
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'movement.pdf')
        document.body.appendChild(link)
        link.click()
    });
  }

推荐阅读