Namako

海參的潮間帶工作室

在 Vue.js 拿到上傳檔案的事件

原本嘗試遵照 在網頁應用程式中使用本地檔案 的方法用onchange事件去提取檔案,卻一直提取失敗。

1
<input type="file" id="input" @change="handleFiles(this.files)">

猜測

猜測可能的原因應該是那個this在寫成 vue 的語法之後遺失了,所以要想辦法繞開。

解法

不指定參數,讓瀏覽器自己傳事件進去

html 模板:

1
<input type="file" id="input" @change="handleFiles">

vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
methods: {
handleFiles: function (element) {
let file = element.target.files[0];
let reader = new FileReader();
reader.onload = () => {
this.convert(reader.result);
};
reader.readAsText(file);
},
convert: function(str){
//TODO
}
}

Hi 喜歡這篇文章的話 可以按個讚或請我喝杯咖啡
Buy me a coffeeBuy me a coffee

目錄