最近在用vue开发,需要做一个文件上传功能。
<form id="uploadForm" enctype="multipart/form-data" style="color:#fff;clear: both;margin-top: 30%;">
<p style="display:inline-block;width:200px;height:30px;border-radius:5px;overflow:hidden;position:relative;left: 33%;">
<span style="display:inline-block;width:200px;height:30px;color:#fff;background:#7d8f33;text-align:center;line-height:30px;" >选择上传文件</span>
<input type="file" name="file" multiple="multiple" id="fileInput" style="position:absolute;left:0;top:0;right:0;bottom:0;opacity:0;" />
</p><br>
</form>
js代码如下
mounted() {
$("#fileInput").on("change",function(){
var _self = this;
_self.applyers = [];
//通过文件名,返回文件的后缀名
if (this.files.length >= 1) {
_self.showPrise = true;
for (var i in this.files) {
var needSuffix = "";
if (this.files[i].size != undefined) {
needSuffix = this.files[i].name.split(".");
_self.applyers.push({
name: needSuffix[0],
size: this.files[i].size + "KB",
type: needSuffix[needSuffix.length - 1]
});
}
}
} else {
_self.showPrise = false;
}
}
})
}
这个方法是可以实现的,但是遇到了一个问题,就是当我关闭我的弹出框时,onchange事件就不触发了,所以我特地去查了onchange的触发机制:
1.input捕获焦点,储存当前值。
2.焦点离开后,判断现值和储存值是否不相等,返回true则触发onchange事件。
所以我尝试手动调用onchange事件,但是失败了。最后发现我的代码是放在mounted中,也就是存在生命周期问题,所以改进了代码如下:
<form id="uploadForm" enctype="multipart/form-data" style="color:#fff;clear: both;margin-top: 30%;">
<p style="display:inline-block;width:200px;height:30px;border-radius:5px;overflow:hidden;position:relative;left: 33%;">
<span style="display:inline-block;width:200px;height:30px;color:#fff;background:#7d8f33;text-align:center;line-height:30px;" >选择上传文件</span>
<input type="file" name="file" multiple="multiple" @change="fileChange($event)" id="fileInput" style="position:absolute;left:0;top:0;right:0;bottom:0;opacity:0;" />
</p><br>
</form>
js:
methods: {
fileChange: function(event) {
var _self = this;
_self.applyers = [];
//通过文件名,返回文件的后缀名
if (event.target.files.length >= 1) {
_self.showPrise = true;
for (var i in event.target.files) {
console.log(event.target.files[i].size);
var needSuffix = "";
if (event.target.files[i].size != undefined) {
needSuffix = event.target.files[i].name.split(".");
_self.applyers.push({
name: needSuffix[0],
size: event.target.files[i].size + "KB",
type: needSuffix[needSuffix.length - 1]
});
}
}
} else {
_self.showPrise = false;
}
}
},
这样就实现了。
关于vue生命周期的问题找到了一篇文章:
https://blog.youkuaiyun.com/running_runtu/article/details/79936503