javascript - VueJS,使用 API 调用刷新组件
问题描述
我是 vuejs 的新手。这就是我想要实现的目标:
- 用户将文件上传到服务器 => 服务器以包含 ID(作业 ID 列表)的 JSON 响应
- 点击提交后,将向用户显示文件处理的状态。(因此遍历作业 ID 列表以获取它们的状态;当作业完成时,作业从列表中删除)=> 因此就像一个进度条。
除了异步问题;我的主要问题是,状态仅在作业结束时显示(即从列表中删除时)。
谢谢您的帮助。
到目前为止,这是我的代码(大括号用于 Django 模板):
<div id="vue-app">
<div>
[[job_ids]]
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" ref="file" v-on:change="handleFileUpload()" name="files" multiple>
<input v-on:click.prevent="submitForm" type="submit" value="submit"></button>
</form>
<ul id="example-1">
<li v-for="item in temp" :key="item.id">
[[item.id]] : [[ item.current]] / [[ item.total ]]
</li>
</ul>
</div>
</div>
const app = new Vue({
el: "#vue-app",
delimiters: ['[[', ']]'],
data: {
myTitle: "é",
success_msg: "http://localhost:8000{% url 'upload_proto' %}",
files: "null",
job_ids: [],
status: {},
temp: {}
},
created() {
setInterval(this.jobsStatus, 5000)
},
methods: {
submitForm: function () {
var formData = new FormData();
formData.append('files', this.files)
for (var i = 0; i < this.files.length; i++) {
let file = this.files[i];
formData.append('files', file);
}
axios.post("http://localhost:8000/proto/upload/", formData,
{
headers: {
'X-CSRFTOKEN':
'{{ csrf_token }}', 'Content-Type':
'multipart/form-data'
}
}
).then(response => {
this.job_ids = response.data;
}).catch(err => {
this.err_msg = err.response.data['err'];
});
},
handleFileUpload: function () {
this.files = this.$refs.file.files;
},
getJobStatus: async function (i) {
return await axios.get("http://localhost:8000/poll_state?job=" + this.job_ids[i])
.then(response => {
this.temp[this.job_ids[i]] = response.data
}
)
.catch(err => {
console.log(err)
})
},
jobsStatus: function () {
for (var i = 0; i < this.job_ids.length; i++) {
this.getJobStatus(i)
if (this.temp[this.job_ids[i]] !== "PENDING") {
if (this.temp[this.job_ids[i]].current === this.temp[this.job_ids[i]].total) {
this.job_ids.splice(i, 1);
}
}
}
return null
}
}
});
解决方案
推荐阅读
- ios - 将 JSON 转换为字符串数组
- node.js - 带有 mysql 承诺的 Node.JS
- python - 从 python Gtk 列表中选择一个选项并将其存储在一个变量中
- node.js - 日期数字格式转换为节点 js 中的月份字符串格式
- amazon-s3 - 数据管道的测试自动化
- javascript - 来自分支的错误:网络请求无效
- cmd - 在 Azure Pipeline 构建中刷新环境变量
- mysql - 足球数据库 - sql 查询 - 无视图 - 进球数最多的球队
- typeorm - 更漂亮:在同一行中保留装饰器中的多个参数
- android-camera2 - 带有 TextureView/AutoFitTextureView 预览的 Camera2 API 在纵向模式下被拉伸