XHR二级增加了progress事件,我们可以据此在浏览器接收新数据期间添加实时数据进度条,从而使得交互更加友好
vue模板
<div class="progress" @click="upload"
:style="{backgroundImage:'linear-gradient(to right,#C0C7CB 0%,#C0C7CB '+progress+',#E1E6E9 '+progress+',#E1E6E9 100%)'}">
vue-js
var form = new FormData()
form.append('file', vm.$refs.upload.files[0])
form.append('id', id)
form.append('type', type)
var config = {
onUploadProgress: progressEvent => {
var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
this.progress = complete
}
}
axios.post(`api/uploadFile`,
form, config).then((res) => {
if (res.data.status === 'success') {
console.log('上传成功')
}
})
关键点在于progress事件,而axios对ajax封装之后需要在axios的config参数里面写好事件处理函数(具体参数写法可查看axios文档)