首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Vue-Ajax上传组件封装

前言:最近在使用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里去实现进度条的上传效果

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200426A0P13G00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券