Problem description

When we do projects, we often need to display images on the page, generally speaking, there are several ways

Method 1 (back end returns image URL)

The imgUrl url is bound to the SRC attribute of the img tag. The following code:

<div class="item" v-for="(item, index) in apiArr" :key="index">
    <! ImgUrl property in each item. Store the url of the image.
    <img :src="item.imgUrl" alt="">
</div>
Copy the code

Mode 2 (use require in front)

The second way is to store the image file in the front end, and the back end returns only the name of the image (or no image data). Example code is as follows:

Code attached

<template>
  <div class="wrap">
    <div class="item" v-for="(item, index) in apiArr" :key="index">
      <div class="imgWrap">
        <! -- require introduce image file module -->
        <img :src="require(`@/assets/img/${item.imgTitle}.png`)" alt="" />
        <! <img SRC ="@/assets/img/first.png" Alt =""> -->
      </div>
      <div class="infoWrap">
        <div><span class="bloder">Result:</span> {{ item.title }}</div>
        <div><span class="bloder">Score:</span> {{ item.score }}</div>
      </div>
    </div>
    
  </div>
</template>

<script>
export default {
  data() {
    return {
      apiArr: [],}; },mounted() {
    ImgTitle property stores the name of the image
    // It will automatically find the corresponding image file in the specified path and load it
    this.apiArr = [
      {
        title: "Champion".score: "98.8".imgTitle: "first"}, {title: "Second".score: "97.9".imgTitle: "second"}, {title: "Third place".score: "96.2".imgTitle: "third",},]; }};</script>
Copy the code

The renderings are as follows

Project document structure diagram

Mode 3 (Front-end import)

Code attached

<template>
  <div class="wrap">
    <div class="item" v-for="(item, index) in apiArr" :key="index">
      <div class="imgWrap">
        <img :src="item.imgTitle" alt="" />
      </div>
      <div class="infoWrap">
        <div><span class="bloder">Result:</span> {{ item.title }}</div>
        <div><span class="bloder">Score:</span> {{ item.score }}</div>
      </div>
    </div>
  </div>
</template>

<script>
// import the image
import first from "@/assets/img/first.png";
import second from "@/assets/img/second.png";
import third from '@/assets/img/third.png'
export default {
  data() {
    return {
      apiArr: [{title: "Champion".score: "98.8".imgTitle: first, // Use the imported image
        },
        {
          title: "Second".score: "97.9".imgTitle: second, // Use the imported image
        },
        {
          title: "Third place".score: "96.2".imgTitle: third, // Use the imported image},]}; }};</script>
Copy the code

The effect drawing and the project file structure diagram are the same as above and will not be described here

conclusion

ES6 import and CommonJS require can be used to import images, but I personally prefer to use require because it is a bit more flexible