Arun D
Arun D

Reputation: 2387

Rendering a javascript image object using VueJs

How to render a javascript image object in the view using VueJs. I have added a sample code below. But the "v-html" tag is not rendering the image.

<div id="test">
  <span v-html="imageTemp"></span>
</div>


<script>
    new Vue({
        el: "#test",

        data: {
            imageTemp: new Image()
        },

        mounted: function() {
            this.imageTemp.src = "/temp.png"
        }
    });
</script>

What is the best method to do this?

I know how to render an image using "v-bind:src".

Also, using jQuery it is possible to add the image object to the view using: $("#test").append(this.imageTemp);

I would like to know whether there is a way to render the javascript image object on the view using VueJs.

Upvotes: 2

Views: 5499

Answers (3)

bbsimonbb
bbsimonbb

Reputation: 29020

The Image object that you use is for creating images in memory, for manipulating them with Canvas and such like. You can use it for displaying an image on the page by appending it to an element, but why do you want to construct your page procedurally like this?

If you want to do this, you need to attach the javascript Image to an element in your doc. In Vue, when you want to access html elements, give them a ref. So...

<div id="test">
  <span ref="putImageHere"></span>
</div> 

<script>
    new Vue({
        el: "#test",
        mounted: function() {
            var img = new Image();
            img.src = "/temp.png"
            this.$refs.putImageHere.appendChild(img);
        }
    });
</script>

v-html is one of those tags to use only when you really need it. v-html snippets are not dynamic.

Upvotes: 1

Raydoan Anik
Raydoan Anik

Reputation: 219

you can use it as simple as possible.

 new Vue({
        el: "#test",
        
      data: {
	imageTemp: '<img src="/temp.png">'
	}
    });
<div id="test">
  <span v-html="imageTemp"></span>
</div>
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

Upvotes: 3

user2080225
user2080225

Reputation:

Why don't you just use an img tag, and then have it's src attrubute be the thing that is getting set dynamically. That's the way it's usually done.

However if for some reason you must have the img tag itself be dynamic then you just need to still go ahead and put the img tag in your template, but just use the 'v-if' to make it render only when needed.

Upvotes: 0

Related Questions