101
76

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.js で画像(ファイル)アップロード直後に表示させる方法

Posted at

バージョン

Vue.js: 2.4.3

サンプル

https://jsfiddle.net/vtexxmh1/1/
vue_upload.gif

方法

v-on でチェンジイベントを取る

.html
<div id="app">
  <h2>↓画像↓</h2>
  <img v-show="uploadedImage" :src="uploadedImage" />
  <input type="file" v-on:change="onFileChange">
</div>

取得したファイルをバインドする

.js
new Vue({
  el: '#app',
  data() {
    return {
      uploadedImage: '',
    };
  },
  methods: {
    onFileChange(e) {
      let files = e.target.files || e.dataTransfer.files;
      this.createImage(files[0]);
    },
    // アップロードした画像を表示
    createImage(file) {
      let reader = new FileReader();
      reader.onload = (e) => {
        this.uploadedImage = e.target.result;
      };
      reader.readAsDataURL(file);
    },
  },  
})
101
76
1

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
101
76

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?