-1

I have a list with several elements (id, name, img_name ). In my asset folder I have a subfolder svgs (srs/assets/svgs). There are the SVGs (logo1.svg, logo2.svg). If I hard code the link it works very well: <img src="@/assets/svgs/brand1.svg" alt="">.

But when I build it dynamically (with a method) it doesn't work. I get a 404. The reason is that it does not interpret @/assets/. He thing it is a string and a part of the path. What i have to change that it works?

<template>
  ... 
  // inside a loop
  <img :src="makeImgPath(item.img_name)" alt="">
  ...
</template>
...
methods() {
    makeImgPath(imgName) {
        return "@/assets/svgs/" + imgName + "svg";
    }
}
...

Network says: 404 newapp/@/assets/svgs/brand1.svg

Max Pattern
  • 1,430
  • 7
  • 18
  • the path needs to be static so the transpiler can detect and change whenever needed. For something like this to work you would need to import all before hand and use something like a hashmap, or use some webpack plugin to detect it and do it for you. – Alykam Burdzaki Sep 19 '22 at 12:30
  • @AlykamBurdzaki Can you explain a little bit more your solution, please? – Max Pattern Sep 19 '22 at 12:31
  • if vue 2 and webpack, take a look at require.context, this answer has some info: https://stackoverflow.com/a/42118921/10922948, I've used it to dynamically import svg Icons on vue2 in the past – Alykam Burdzaki Sep 19 '22 at 12:54
  • what about and `makeImgPath` method will return only .jpg – Debug Diva Sep 19 '22 at 13:04
  • you can try, I don't think it will work though, resolving part of the name in the transpilling and part on running time. – Alykam Burdzaki Sep 19 '22 at 13:24

1 Answers1

1

As you have correctly pointed out, vue does not interpret @/asstes. @ also only stands for src/. For this reason, you can replace the @ with src, then it should work.

    makeImgPath(imgName = 'defaultImageName') { // suggestion
        return "src/assets/svgs/" + imgName + "svg";
    }
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79