SoFunction
Updated on 2025-03-02

Method of using variables in picture Src in Vue

I believe that many students have encountered the situation in the development of image paths that require variable introduction, such as customized backgrounds, dynamic display avatars, etc. Maybe the following mistakes have been made

# Error description

The plan for directly calling image resources on the page

<img src="../../static/images/web_bg.png" />

Rewrite it into a variable form, so it is written as follows

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

<script>
export default {
 data() {
  return {
   imgSrc: '../../images/web_bg.png'
  }
 }
}
</script>

As a result, the running image failed to load. What's the reason? It turns out that the hash value will be automatically added during packaging, resulting in a difference.

# Solution

1. Use image resources on the Internet

data() {
 return {
  imgSrc: '/files/images/'
 }
}

2. Use import to import local resources

import imgSrc from '../../images/web_bg.png'
export default {
 data() {
  return {
   imgSrc: imgSrc
  }
 }
}

3. Import using require

data() {
 return {
  imgSrc: require('../../images/web_bg.png')
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.