Vue-Ajax上传组件封装

最近在使用vue写页面,所以自动封装了一个ajax封装组件,vue相对来说还是比较简的,只要名白数据绑定是怎么会事就很好学习了,类似相关的框架有微信小程序也是基于数据绑定的方式。

代码
//封装VUE AJAX FILE COMPONENT
Vue.component('my-file', {  
    template: '<input type="file" @change="uploadFile" id="file_upload_id"/>',
    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对象之前注册
使用方式:
< my-fiel>< /my-file>

接下来放一段原生的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里去实现进度条的上传效果

郝先生

继续阅读此作者的更多文章