【问题标题】:Vue - reload data after href download startsVue - href 下载开始后重新加载数据
【发布时间】:2022-01-18 16:20:30
【问题描述】:

我正在打一个简单的window.location.href 电话以开始下载文件。之后,我调用一个方法来重新加载一个表。

window.location.href = url;
this.getFileListing();

但是重新加载太快了,因为href创建了一个数据库记录。

添加 1 秒超时修复它:

window.location.href = url;
setTimeout(() => {
    this.getFileListing();
}, 1000);

...但这太草率了。在调用重新加载之前如何等待下载开始(因此数据库记录将存在)?

*注意:窗口的位置不会改变。我只是使用 windows.location.href 来调用本地路由,该路由开始下载文件。因此,我不相信 popstate 或 hashchange 会起作用。

【问题讨论】:

标签: javascript ajax vue.js


【解决方案1】:

您可以使用 axios 下载文件并使用 then 方法来启动所需的方法,而不是使用 window.location.href 启动下载。

 axios({
   url: url,
   method: 'GET',
   responseType: 'blob'
 .then(response => (this.getFileListing()))

如果您使用的是 jQuery,您可以尝试与 jquery get https://api.jquery.com/jquery.get/ 等效的方法

var instance = this;
$.get("fileToDownload", function() {
    //code when download is launch
}).done(function() {
    instance.getFileListing();
})

【讨论】:

  • 好主意!但是,我只能访问 jQuery,而不是 axios(不是我的决定)。
  • 它运行我在我的回复中添加了一个带有 jquery usign 的示例
【解决方案2】:

我的解决方案:使用 axios 和大量代码来获取响应,并将其传递给浏览器。我不得不解析出原始文件名。不确定是否值得。我实际上将这些函数放在了一个 mixin 中,这样我就可以轻松地将它添加到其他组件中。

downloadToBrowser(url, successCallback) {
  axios({
    method: 'GET',
    url: url,
    responseType: 'blob'
  })
  .then(response => {
    this.startDownload(response);
    successCallback();
  });
},
startDownload(response) {
  var filename = response.headers['content-disposition'].split('=')[1];
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
},

然后调用方法,传入url和回调:

this.downloadToBrowser(url, this.getFileListing);

*如果您对我可以做得更好/不同的事情有任何意见,我欢迎反馈。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 2016-10-01
    • 2013-09-07
    • 2018-05-12
    • 1970-01-01
    相关资源
    最近更新 更多