1

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?

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Boussadjra Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.