Using v-bind:src with Vue

Aug 29, 2022

You can dynamically control the image an <img> tag displays using the v-bind:src, or :src for short, binding. This allows you to insert JavaScript in the attribute field.

methods

Using :src, you can set the image's src to the result of a Vue method.

<script>
  const { createApp } = Vue

  createApp({
    methods: {
      getPhoto() {
        return '../../assets/logo.png';
      }
    },
    template: `
    <img :src="getPhoto()" />
    `
  }).mount('#app');
</script>

computed

A computed property allows you to have logic that is dependent on reactive data. In the example below, should value change, the logo image will no longer be displayed.

<div id="example"></div>

<script>
  const { createApp } = Vue

  createApp({
    data: function() {
      return {
        value: 0
      }
    },
    computed: {
        photo() {
          return this.value == 0 ? '../../assets/logo.png' : 0
        }
    },
    template: `
    <img :src="photo" />
    <div>
      <button @click="value > 0 ? value-- : value++">Click</button>
    </div>
    `
  }).mount('#example');
</script>

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