LoginSignup
2
4

More than 5 years have passed since last update.

Vue.js + axiosを使ってaxiosのレスポンスから動的に画像を生成する方法

Last updated at Posted at 2018-10-20

タイトルの通りですが、Vue + axiosを使って開発していた所、axiosのレスポンスから動的に画像を生成するという事で少し詰まったので共有します。

まず、axiosで返ってきた値を使ってdataで定義したimageDataをにセットします。

  data () {
    return {
      imageData = null
    }
  },
  mounted: function () {
    axios.get('APIのエンドポイント')
      .then(function (res) {
         this.imageData = res.data.image_id
      })
  }  

そして次にmethodsで関数 create_image を定義します。

methods: {
  create_image: function () {
    return require('画像ファイルのあるPATH' + this.imageData + '.png')
  }
}

そして最後にtemplate側で

<template>
  <div>
    <img :src="create_image()">
  </div>
</template>

とします。

まとめると

<template>
  <div>
    <img :src="create_image()">
  </div>
</template>

<script>
export default {
  data () {
    return  {
      imageData = null
    }
  },
  mounted: function () {
    axios.get('APIのエンドポイント')
      .then(function (res) {
         this.imageData = res.data.image_id
      })
  },
  methods: {
    create_image: function () {
      return require('画像ファイルのあるPATH' + this.imageData + '.png')
    }
  }
}

となります。

また生成する画像が複数の場合は下記のようにします。

<template>
  <div>
    <p v-for="i in imageData" :key="image.id"><img :src="create_image(i)"></p>
  </div>
</template>

<script>
export default {
  data () {
    return  {
      imageData = []
    }
  },
  mounted: function () {
    axios.get('APIのエンドポイント')
      .then(function (res) {
         this.imageData = res.data.image_id
      })
  },
  methods: {
    create_image: function (i) {
      return require('画像ファイルのあるPATH' + i + '.png')
    }
  }
}

ここで1つ注意点なのですが、おそらくこのままだと正常に動作はするのですがコンソールに Error: Cannot find module './undefined.png'というエラーが出ると思うので、その時は create_image関数で

return n ? require('画像ファイルのあるPATH' + i + '.png') : ''

とnullチェックをすれば回避できます。

間違えてる所やもっといい書き方等があったらコメントを頂けると嬉しいです!

2
4
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
2
4