2017-04-24 12 views
1

Vue.jsでファイルピッカーを開発しています。選択したファイルのプレビューを表示したい。 私はこれを達成するためにFileReaderAPIを使用します。私はFileReaderオブジェクトのreadAsDataURLメソッドでデータURLとしてユーザーが選択したファイルを読んでいます。Vue.jsコンポーネントメソッド内でFileReader APIを使用する

私はreader.onloadは次のように関数ではないというエラーメッセージを取得しかし:それは読者が私は上記しているFileReaderの未定義エラー以下、定義されていないことがあり

Uncaught TypeError: reader.onload is not a function 
    at VueComponent.handleFileChanges 

を。次のように私はこれを行うやろうどのよう

は次のとおりです。

handleFileChanges (e) { 
    var reader = new window.FileReader() // if window is not used it says File READER is not defined 
       reader.onload(function (event) { 
        // dispatch fileAttached to state UI postEditor with event.target.result as read dataURL 
        let imageDataURL = event.target.result 
        this.$store.dispatch('attachedFile', imageDataURL) // or previewFile 
       }) 
       reader.readAsDataURL(e.target.files[i]) 
} 

私が行方不明ですポイントは何ですか?

答えて

2

よく、エラーといい、それは機能ではありません。基本的にonloadは、新しく構築されたFileReaderオブジェクトに添付されたイベントハンドラ/プロパティであり、関数ではないためコールバックを受け入れません。

はこのようにそれを使用します。

handleFileChanges (e) { 
    var reader = new window.FileReader() // if window is not used it says File READER is not defined 
       reader.onload = function (event) { 
        // dispatch fileAttached to state UI postEditor with event.target.result as read dataURL 
        let imageDataURL = event.target.result 
        this.$store.dispatch('attachedFile', imageDataURL) // or previewFile 
       } 
       reader.readAsDataURL(e.target.files[i]) 
} 

this.$store.dispatchthisがコンテキストを修正するために制限されていることを確認します。

1

onloadはプロパティであるため、コールバックとして設定(変更)する必要があります。しかし、FileReaderEventTargetから継承していますが、すべてのイベント(onload、onabortなど)はaddEventListenerで使用できます。ですから、どのような場合でも、オンロードのイベントハンドラとしてコールバックを渡す必要がある場合は、addEventListenerを使用すると考えられます。

// method 1 
reader.onload = function (e) { ... 
// method 2 
reader.addEventListener("onload", function (e) { ... 
関連する問題