Vue-CLIで、テキストファイルをファイル入力ボックスから読み込んで、中身(テキスト)を単に表示させるだけだったが、thisの使い方にハマった。function内のthisは、インスタンス内でそのインスタンスを指すので注意。
Vueファイルコード
*.vue
<template>
<div>
<form>
<input type="file" @change="readfile" />
</form>
<div>{{ data }}</div>
</div>
</template>
<script>
export default {
data(){
return {
data: []
}
},
methods: {
readfile: function(e) {
const vm = this
const file = e.target.files[0]
const reader = new FileReader()
reader.onload = function() {
vm.data = reader.result
}
reader.readAsText( file )
}
}
}
</script>
参考
onloadイベントのfunction内で、thisを使うと上手く行かない。この場合、アロー関数を使えば上手く動く。
// A.動作しない
reader.onload = function() { this.data = reader.result }
// B.動作する
reader.onload = () => this.data = reader.result
console.logでthisの正体を調べたところ、function内のthisはFileReaderインスタンスを参照していた。
// thisの正体
A FileReaderインスタンスを参照 -> FileReader {readyState: 2, result: …}
B Vueインスタンスを参照 -> Proxy {readfile: ƒ, …}