I'm trying to bind image src dynamically to a url in a v-for loop as below :
<script>
export default {
name: 'Home',
data() {
return {
games: [
{"gameId": 1365, "gameLabel": "ssbu"},
{"gameId": 1366, "gameLabel": "ggs"},
{"gameId": 1367, "gameLabel": "sf5"},
]
}
}
};
</script>
<template>
<div v-for="game in games"">
<img :src="`../assets/cards/${game.gameLabel}.jpg`" :alt="game.gameLabel">
</div>
</template>
But I had the error GET http://localhost:3000/assets/cards/ssbu.jpg 404 (Not Found)
although it works fine when I do this : <img src="../assets/cards/ssbu.jpg" :alt="game.gameLabel">
.
So i tried using require function as people mentionned in other posts with something like this : <img :src="require(`../assets/cards/${game.gameLabel}.jpg`)" :alt="game.gameLabel">
but there I faced the fatal error ReferenceError: require is not defined
.
SO I'm stuck at this point and I need your help in order to resolve this problem.
Thanks in advance.
CodePudding user response:
Put your images into the static folder.
rename to:
Now you have a cards
folder inside the static folder
CodePudding user response:
Everything in the assets folder will be handled by Webpack while everything in the public folder is simply copied but does not go through Webpack. So if you want to take advantage of the optimization features of the webpacks during the build put them in assets. The assets folder is usually where you will place your images / videos / fonts / svgs etc. that you will import into view files. Items from the assets folder that you don't explicitly import will not end up in your dist folder, so as not to inflate the final size of your file.
To access the images in the assets folder in Vue, we would:
:src = "require('@/assets/images/myimage.jpg')"
To access the images in the public folder in Vue, we would:
:src="./static/images/myimage.jpg"