Reputation: 2377
I think this is a simple question, though don't get why it fails. I am trying to fetch a local image in nuxt assets folder.
My guess is that Im doing "~" in a string, and thats the reason, but I can't seem to get the image load.
I have tried with following code to access a local image in my nuxt project:
<template>
<div class="background-image" :style="`background-image: url(${imageSource})`">
</div>
</template>
And this is my scripting:
<script>
export default {
data() {
return {
defaultCoverImage: '~/assets/images/covers/default-cover.jpeg',
}
},
computed: {
imageSource() {
if(this.src.match(/\.(jpeg|jpg|gif|png)$/)) {
return this.src;
}
return this.defaultCoverImage;
}
}
};
</script>
The image does not show up or load correctly. Please check the folder structure below. The red line is the root folder.
Upvotes: 0
Views: 2304
Reputation: 2377
For somebody else who might have the same issue, this is how I solved it (with inspiration of kissus answer below:
data() {
return {
defaultCoverImage: require('~/assets/images/covers/default-cover.jpeg'),
}
}
Upvotes: 2
Reputation: 46696
This answer may help: https://stackoverflow.com/a/68095775/8816585
Also, this should be enough
<div :style="{ backgroundImage: `url(${require('~/assets/images/covers/default-cover.jpeg')})`}">
</div>
Upvotes: 1