0
0

More than 3 years have passed since last update.

Vue.js テキストファイルを読み込み表示させる

Last updated at Posted at 2021-05-29

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: ƒ, …} 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0