in Vue I am trying to use the result from a method as the source for an image:
HTML:
<img :src="getEnergyIcon(type)">
JS:
data() {
return {
energyTypeMap: new Map([
['colorless','@/assets/images/energy-icons/20px-Colorless-attack.png'],
['darkness','@/assets/images/energy-icons/20px-Darkness-attack.png'],
['dragon','@/assets/images/energy-icons/20px-Dragon-attack.png'],
['fairy','@/assets/images/energy-icons/20px-Fairy-attack.png'],
['fighting','@/assets/images/energy-icons/20px-Fighting-attack.png'],
['fire','@/assets/images/energy-icons/20px-Fire-attack.png'],
['grass','@/assets/images/energy-icons/20px-Grass-attack.png'],
['lightning','@/assets/images/energy-icons/20px-Lightning-attack.png'],
['metal','@/assets/images/energy-icons/20px-Metal-attack.png'],
['psychic','@/assets/images/energy-icons/20px-Psychic-attack.png'],
['water','@/assets/images/energy-icons/20px-Water-attack.png'],
])
}
},
And:
methods: {
getEnergyIcon(type){
return this.energyTypeMap.get(type.toLowerCase());
}
},
The method returns the correct path, but the image doesn't use that path as the source:
I want the result to be the same as the hardcoded result, but I want to achieve this by using the method, because I am going to use dynamic data that gives me one of the 11 types, I cannot use hardcoded paths.
I have been Googling around to find a solution but I can't find a solution that uses a direct method as a source for the image. How do I do this?
Thanks in advance.
Found this topic:
How to reference static assets within vue javascript
That mentioned the following:
In a Vue regular setup, /assets is not served.
The images become src="..." strings, instead.
And required me to use:
require();
Which I did like this:
data() {
return {
card: {},
energyTypeMap: new Map([
['colorless',require('@/assets/images/energy-icons/20px-Colorless-attack.png')],
['darkness',require('@/assets/images/energy-icons/20px-Darkness-attack.png')],
['dragon',require('@/assets/images/energy-icons/20px-Dragon-attack.png')],
['fairy',require('@/assets/images/energy-icons/20px-Fairy-attack.png')],
['fighting',require('@/assets/images/energy-icons/20px-Fighting-attack.png')],
['fire',require('@/assets/images/energy-icons/20px-Fire-attack.png')],
['grass',require('@/assets/images/energy-icons/20px-Grass-attack.png')],
['lightning',require('@/assets/images/energy-icons/20px-Lightning-attack.png')],
['metal',require('@/assets/images/energy-icons/20px-Metal-attack.png')],
['psychic',require('@/assets/images/energy-icons/20px-Psychic-attack.png')],
['water',require('@/assets/images/energy-icons/20px-Water-attack.png')],
])
}
},
It has solved my problem.