'Vue cannot find module image location
I'm having a problem with my project not finding the path to my png images. I know the path is correct because if I use a basic hard coded src="../assets/die1.png", it works fine. The problem is I need them to changed based on other data.
I keep getting the error: Cannot find module '../assets/die1.png'
COMPONENT:
<template>
<div class="DiceComponent col-3 bg-primary">
<img v-if="die.output != ''" :src="require(die.output)" alt="error loading image" />
</div>
</template>
NOTE: die.output == "../assets/die1.png" and this is confirmed in the Vue devtool.
Solution 1:[1]
I am getting some error in your store functions that I can solve now so I focused on the image question. As you are working with static files, I've moved them to public folder and have made a simple rollDice function:
rollDice() {
let rng = Math.floor(Math.random() * 6);
this.diceTemp = `./die${rng+1}.png`
},
then:
<Die :die="diceTemp" />
inside the component:
<img :src="die" />
and this works fine! Somethings to consider:
- If you are using stores you can use die values inside your Die component and avoid using nested values (die.output) props (vuejs.org/v2/guide/reactivity.html)
Solution 2:[2]
For readability you can change your output variable to:
die.output == require('../assets/die1.png')
or
die.output == require('@/assets/die1.png')
And then
<template>
<div ...>
<img ... :src="die.output" ... />
</div>
</template>
Solution 3:[3]
Replace what you have now with
<template>
<div ...>
<img ... :src="require(`${die.output}`)" ... />
</div>
</template>
Solution 4:[4]
It was hard but I found a way
try this:
let imgName = "logo-blue.svg";
getLogo(imgName) {
const partName = imgName.split("logo-")[1];
return require("../img/logo-" + partName);
}
I don't know why, but if you do return require("../img/" + imgName);
it doesn't work, just with the split it's working.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Franco Mitoire |
Solution 3 | Tony |
Solution 4 | Michel Fernandes |