October 3, 2022

Robotic Notes

All technology News

Working with the img HTML Tag in Vue

1 min read


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="https://masteringjs.io/tutorials/vue/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="https://masteringjs.io/tutorials/vue/photo" />
    </div>
  `,
  computed: {
    photo() {
      return '../../assets/logo.png';
    }
  }
});

Class src

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

const decor = new Vue({
  data: () => ({
    active: false
  }),
  template: `
    <div style="width: 50%">
      <img :class="imageClass" :src="https://masteringjs.io/tutorials/vue/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!


More View Tutorials



Source link