Vue dynamically binds image addresses, and the solution to the problem that using require also fails

Let’s first look at the effects of displaying pictures in 4 ways
Insert image description here

code:

<div v-if="weather">
  {
   
   { weather.location.name }} | {
   
   { weather.now.text }} | {
   
   { weather.now.temperature }}℃
  <img src="../../assets/img/weather/0.png" alt="" style="width:40px;height:40px;" />
  <img :src="iconUrl" alt="" style="width:40px;height:40px;" />
  <img :src="require('../../assets/img/weather/0.png')" alt="" style="width:40px;height:40px;" />
  <img :src="require('../../assets/img/weather/' + imgName)" alt="" style="width:40px;height:40px;" />
</div>
data() {
    
    
  return {
    
    
    weather: "",
    iconUrl: require('../../assets/img/weather/0.png'),
    url: "../../assets/img/weather/0.png",
    imgName: '0.png',
  }
},

I believe many people will use the second method to dynamically bind addresses, but the picture cannot be displayed because:

The vue project will compress the code when running the package, thereby modifying the absolute path in iconUrl. If we do not modify the iconUrl in data, an error will be displayed. As for require('image storage path' + imgName), the reason for writing the image storage path is because with the image storage path, he will enter the image storage path to find imgName. If he does not write the image storage path, he will go to the ./ path to search. imgName.

Solution:
Similar to the fourth solution, take out the picture name separately and dynamically replace the picture name to achieve dynamic binding display of the picture.

Guess you like

Origin blog.csdn.net/TurtleOrange/article/details/126872319