前言:最近在使用vue写页面,所以自动封装了一个ajax封装组件,vue相对来说还是比较简的,只要明白数据绑定是怎么个情况就很好学习了,类似相关的框架有微信小程序也是基于数据绑定的方式。
代码
//封装VUE AJAX FILE COMPONENT
Vue.component('my-file', {
template: '',
methods: {
uploadFile: function () {
var fd = new FormData();
fd.append("upload", document.getElementById("file_upload_id").files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", this.uploadProgress, false);
xhr.addEventListener("load", this.uploadComplete, false);
xhr.addEventListener("error", this.uploadFailed, false);
xhr.addEventListener("abort", this.uploadCanceled, false);
xhr.open("post", "/files");
xhr.send(fd);
},
uploadProgress: function (event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
vm.age = percentComplete.toString() + '%';
}
else {
vm.age = 0;
}
},
uploadComplete: function (event) {
console.log('complete');
},
uploadFailed: function (event) {
console.log('failed');
},
uploadCanceled: function (event) {
console.log('abort');
}
}
});
var vm = new Vue({
delimiters: ['[[', ']]'],
el: '#example-3',
data: {
message: "",
messageArr: [],
age: ""
},
methods: {
say: function (message) {
alert(message)
}
}
});
//注意,vue component 必须在vue对象之前注册
使用方式
原生的js-ajax-upload.js
var ajaxUploadFile = function () {
var fd = new FormData();
fd.append("upload", document.getElementById("file_id").files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("post", "/files");
xhr.send(fd);
};
var uploadProgress = function (event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded * 100 / event.total);
vm.age = percentComplete.toString() + '%';
}
else {
vm.age = 0;
}
};
var uploadComplete = function (event) {
console.log('complete');
};
var uploadFailed = function (event) {
console.log('failed');
};
var uploadCanceled = function (event) {
console.log('abort');
};
以上的的都是带请求处理的进度条的,大家可以使用uploadProgress里去实现进度条的上传效果
领取专属 10元无门槛券
私享最新 技术干货