Home » vue » Render local image in Vue component where image location is stored in data attribute

Render local image in Vue component where image location is stored in data attribute

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m trying to render an image from my assets folder in a Vue project. The image displays when I hardcode it in using any of the following methods:

<img src="../assets/my_image.jpg"></img>
<img :src="require('../assets/my_image.jpg')"></img>
<img src="@/assets/my_image.jpg"></img>
<img :src="require('@/assets/my_image.jpg')"></img>

However I can’t get the image to render I store that location in a data attribute called imgLocation, where imgLocation='../assets/my_image.jpg' or imgLocation='@/assets/my_image.jpg':

<img :src="imgLocation"></img>
<img :src="require(imgLocation)"></img>

The first element shows no image and logs nothing to the console. The second element shows the following errors in the console:

[Vue warn]: Error in render: “Error: Cannot find module ‘@/assets/my_image.jpg'”

Error: Cannot find module ‘@/assets/my_image.jpg’
at webpackEmptyContext (eval at ./src/components sync recursive (app.js:6618), :2:10)

Any idea what I’m doing wrong here?

Answers:

In the second case the bindings are evaluated at run-time. You want the path to be resolved at build-time. So you should probably do imgLocation: require('../assets/my_image.jpg') or imgLocation: require('@/assets/my_image.jpg') in the data section of your component.