Setting image src property with VueJS requires datatype “string”

Posted by admin at January 5, 2021

When binding the src property of an image, the URI string pointing to the location of the image file is required. The following line shows how it should be properly done with VueJS

<!--Hardcoding the file path to the img tag-->
  <img src="https://blinkwiki.com/file.path.jpeg" />

But when using Vue, one would expect it to be done the following way. First we setup the Vue store


let app = new Vue({
  el: "app",
  data: {
    filePath: "https://blinkwiki.com/file.path.jpeg",
  },
})

Next we use the key from the Vue store to set the img src property dynamically.

<!--Setting it with VueJS store-->
  <img v-bind:src="filePath" />

This is supposed to work but it results in an error which causes the image not to load at all.

The Solution:

Vue requires a datatype of string to be sent to the v-bind:src property. And nothing but string! Even though we set the Vue data.filePath node to a string value “https://blinkwiki.com/file.path.jpeg”, we still need to ensure that this value is a string.

Therefore to correct this, we use the toString() method when setting the v-bind:src= property:

<img v-bind:src="filePath.toString()" />

Or appending the data store key to an empty string will also do the trick:

<img v-bind:src="'' + filePath" />

For some reason setting this property for an image tag <img> requires a string datatype which is not mandated for other v-bind directives.


            
            
        
    
                      
        0 likes
    

    
            
			        
	    				
						
						
                    
		        
	        
	

Suggested Read