SoFunction
Updated on 2025-03-10

How to dynamically bind img's src attribute (ternary operation)

Vue2.0 dynamically binds the src attribute of img (ternary operation)

In the vue project, if you need to dynamically judge the src address of img, the method is as follows:

Method 1

When judging ternary operators in the tag, require() is required on the outer layer of the reference address

requireThe function parses the image path when it is built and packages the image to the correct location.

Use require to ensure that the path is parsed correctly when packaged.

<img :src="?require('@/assets/images/passed_big.png'):require('@/assets/images/passed_big2.png')" alt="">

Method 2

Use computed attribute to dynamically calculate the src path of img

&lt;template&gt;
  &lt;div&gt;
    &lt;img :src="getImageSrc" alt=""&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data() {
    return {
      checkResult:true
    };
  },
  computed: {
    getImageSrc() {
      return 
        ? require('@/assets/images/passed_big.png')
        : require('@/assets/images/passed_big2.png');
    }
  }
};
&lt;/script&gt;

&lt;style scoped&gt;
/* Your style */
&lt;/style&gt;

Method 3

dynamicimportCan be used to load resources at runtime, but this approach is often used in more complex scenarios such as loading modules on demand

<template>
  <div>
    <img :src="getImageSrc" alt="">
  </div>
</template>
export default {
  data() {
    return {
      checkResult:true
      imageSrc: ''
    };
  },
  async created() {
     = 
      ? await import('@/assets/images/passed_big.png')
      : await import('@/assets/images/passed_big2.png');
  }
};

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.