SoFunction
Updated on 2025-04-07

Correct way to write dynamically load images of Vue project

1. Wrong writing

The following situations run abnormally and the picture cannot be loaded

<img class="img" :src="imgSrc" />
<script>
let imgSrc = '../../assets/';
</script>

2. Correct practical writing method

Method 1

At this time, you need to change the writing method and let the images be added together during compilation processing

Reason: webpack will load the image as a module when compiling. However, the first point above is dynamic, and the loader cannot parse the image path, so the compilation rules cannot process it, so the image cannot be found during loading.

<img class="img" :src="imgSrc" />

<script>
import img1 from '../../assets/'
let imgSrc = img1;
</script>

Method 2

Put the image resources in a static directorystatic, when citing, it is directly referenced by a fixed address

assetsandstaticDifferences:
assets: During the project compilation process, it will be resolved into module dependencies by webpack processing, and only supports the form of relative paths.
static: In the static directory, the file will not be processed and parsed by webpack, and the webpack will be copied directly to the final packaged directory dist/static. These files must be referenced using an absolute path.

<img src="/static/" />

Attachment: Dynamic loading of image paths in vue

The path to loading an image in vue is different from the path we introduce without using a framework. If used in the page, the written path can take effect, but if we want to dynamically load the image path, it will not take effect.

Here are two ways to solve it:

Method 1: (Recommended)

1. On the page, bind the dynamic path:

<img :src=" imgUrl "/> 

2. In data: use require (image path)

 data(){
      return{
        imgUrl:require('@/assets/img/mind/mind_5.svg');
    }
}

Method 2:

Just put the picture in static and get the picture relative to the path

src: '../../../../static/images/'

Summarize

This is the article about the correct writing of Vue project dynamic loading pictures. For more related Vue dynamic loading pictures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!