LoginSignup
1
1

More than 3 years have passed since last update.

[Vue.js] 画像をプレビュー表示する

Last updated at Posted at 2021-01-19

今回の題

ユーザーがformに入力した画像をプレビュー表示する機能を実装してみようと思います。

デモ

実装

1 fileアップロード用のinputを作成。

changeイベントとプレビューを表示するための関数を結びつけ、画像が選択されたら処理が発火するようにする。refを使用してファイルオブジェクトを取得できるように。

<input type="file" ref="image" @change="showPreview">

2 プレビュー用の関数の作成

this.$refs.image.files[0]でユーザーが選択した画像のファイルオブジェクトを取得。
createObjectURLを使用してファイルオブジェクトURLを作成。

methods: {
  showPreview: function() {
    if (this.imageUrl) {
      URL.revokeObjectURL(this.imageUrl) 
    }
    const file = this.$refs.image.files[0]
    this.imageUrl = URL.createObjectURL(file)
    }
}

すでにオブジェクト URL が生成されている場合でも、 createObjectURL() を呼び出す度に、新しいオブジェクト URL が生成されます。 必要がなくなったら URL.revokeObjectURL() を呼び出して、それぞれを解放してください。
createObjectURLから引用

だそうなので、2回目以降のアップロードの際は最初のif文で既存のものを解放してあげます。

3 作成したオブジェクトURLを管理するプロパティの作成。

data: {
  imageUrl: null
}

4 プレビューを表示するimgタグを配置

オブジェクトURLを管理するプロパティとsrc属性をバインド。
v-showでオブジェクトURが存在する場合のみ表示するように設定しました。

<img :src="imageUrl" v-show="imageUrl" width="100" height="100">

全体コード

<div id="app">
  <img :src="imageUrl" v-show="imageUrl" width="100" height="100">
  <input type="file" ref="image" @change="showPreview">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app = new Vue({
  el: '#app',
  data: {
    imageUrl: null
  },
  methods: {
    showPreview: function() {
      if (this.imageUrl) {
        URL.revokeObjectURL(this.imageUrl) 
      }
      const file = this.$refs.image.files[0]
      this.imageUrl = URL.createObjectURL(file)
    }
  }
});
</script>

以上!!

1
1
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
1
1