How to build Vue dynamic assets (image) path?

Viewed 29

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

1 Answers

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";
    }
Related