Riku
Riku

Reputation: 758

How to render Image Object on Vue

Is it possible to render an image object that has prop of source??

<template>
  <div v-html="image">
    {{ image }}
  </div>
</template>
<script>
export default {
  data () {
    return {
      image: new Image(),
      loading: true
    }
  },
  props: ['source'],
  created () {
    console.log(this.image)
    if (this.image) {
      this.image.onload = function (event) {
        console.log(event)
      }
      this.image.src = this.image
    }
    // this.src = this.image
  }
}
</script>

<style>

</style>

I just want to know if the props source is loaded then, i will render it. otherwise Ill render something else, but i didnt include it on the snippet.

Thanks!

Upvotes: 2

Views: 7882

Answers (1)

artoju
artoju

Reputation: 1712

You can do

<template v-if="source">
    <img :src="source"/>
</template>
<template v-else>
 //something else
</template>

Or with placeholder image.

<template>
  <div>
    <img :src="image"/>
  </div>
</template>
<script>
export default {
  mounted: function() {
    if (this.source) { //is it empty
      this.image = this.source //replace placeholder
    }
   this.loading = false
  },
  data () {
    return {
      image: somePlaceholderImage,//url for placeholder image
      loading: true
    }
  },
  props: ['source'],
}
</script>

<style>

</style>

Upvotes: 5

Related Questions