SoFunction
Updated on 2025-04-10

Detailed explanation of the method of citing local image paths in Vue3

Today, when I was working on the Vue3 project, my brain suddenly became a little short-circuited when I referenced the local image path.

When loading local images using the el-image component, it is always prompted to fail, and the image cannot be displayed.

Using require certainly doesn't help, because my project uses Vite for scaffolding.

So, today I have sorted out the problem of citing local image paths in Vue3, and I hope it can help friends who have a sudden short circuit in their brain like me.

Two cases of reference implementation

1. Use in the template

First of all, we should note that the img element is used here, not image UI components such as el-image. At this time, both relative or absolute paths are possible.

<template>
    <img style="width: 100px; height: 100px" src="@/assets/" />
</template>

In the project built by Vite scaffolding, the following situations are not acceptable. You can only use the method we mentioned below in logic!

<el-image :src="require('@/assets/')" />  //X
<el-image :src="require('../assets/')" />  //X

<el-image src="@/assets/" /> //X  
<el-image src="../assets/" />  //X

In projects built by Vue-cli scaffolding, it must be equipped with a require, and it is not possible to directly use relative paths or absolute path references!

<el-image :src="require('@/assets/')" />  //√
<el-image :src="require('../assets/')" />  //√

<el-image src="@/assets/" />  //X
<el-image src="../assets/" />  //X

2. Use in logic

It is basically OK to master the regular usage of Vue3.

<template>
    <el-image style="width: 100px; height: 100px" :src="accIcon" />
</template>

<script setup>
import accIcon from "@/assets/"
</script>

If you are a Vue2 project, use require in logic or templates.

Knowledge Supplement

1. Use directly

<template>
  <img src="./image/"/>
</tempalte>

Use require

<template>
  <img :src="imgUrl">
</template>
<script>
export default {
  data() {
    return {
      imgUrl:require('./image/')
    }
  }
}  
</script>

Use import to enter

<template>
  <img :src="imgUrl">
</template>
<script>
import img from './image/'
export default {
  data() {
    return {
      imgUrl:img
    }
  }
}  
</script>

4. Use life cycle

<template>
  <img :src="imgUrl">
</template>
<script>
export default {
  data() {
    return {
      imgUrl:''
    }
  },
 created() {
    let urlImg = "pages/MSite/image/"
     = require("@/"+urlImg)
  }
}  
</script>

This is the introduction to this article about the detailed explanation of the method of quoting local image paths in Vue3. For more related contents of quoting local image paths in Vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!