Working with the img HTML Tag in Vue

May 9, 2022

To display an image with the img tag in vue, you can usev-bind:src directive, or :src. Or :src for short. Remember that :src expects a JavaScript expression, so if you want to use a string literal in :src you need to wrap the string in quotes.

Below is an example of using :src to display images two different ways: a raw string literal, or a variable in data.

const app = new Vue({
  data: function() {
    return {
      link: '../../assets/logo.png'
    };
  },
  template: `
    <div>
      <div style="width: 50%">
        <img :src="'../../assets/logo.png'" />
      </div>
      <div style="width: 50%">
        <img :src="link" />
      </div>
  </div>
  `,
});

Below is a live example.

Computed src

You can also pass a computed property to :src. Just make sure the computed property returns the

const example = new Vue({
  template: `
    <div style="width: 50%">
      <img :src="photo" />
    </div>
  `,
  computed: {
    photo() {
      return '../../assets/logo.png';
    }
  }
});

Class src

You can set conditional classes on an image using v-bind:class, or :class for short.

const decor = new Vue({
  data: () => ({
    active: false
  }),
  template: `
    <div style="width: 50%">
      <img :class="imageClass" :src="photo" />
    </div>
  `,
  computed: {
    photo() {
      return '../../assets/logo.png';
    },
    imageClass() {
      return { active: this.active };
    }
  },
  mounted() {
    this.active = true;
  }
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!