How to bind img src in Vue.js

in Code Write a comment

Learn the basics of binding data to the HTML image tag using Vue.js.

You can build static websites, MVPs and prototypes with single page applications (SPAs). Sometimes you deal with more complex cases such as building large applications, working with APIs and authentication.

Vue.js is good at both. And today we’ll be dealing with dynamic images. Think about the user profile picture that is fetched from the backend server with an API get request.

How to use img src in Vue.js

You should use a Vue.js v-bind:src or just :src to dynamically set image src.

new Vue({
  el: "#app",
  data: {
    image: 'https://picsum.photos/id/1005/600/200'
  }
})
<div id="app">
  <h2>Image:</h2>
  <img :src="image" style="width:100%;" alt="">
</div>

Hi, I'm Renat 👋

âžœ  


Another example

The example below shows how to get a dynamic image from the third-party service when you click on the Get a dynamic image button. It will then bind this image to the HTML image tag.

new Vue({
  el: "#app",
  data: {
    userProfilePic: null
  },
  methods: {
    getImage () {
      this.userProfilePic = 'https://picsum.photos/id/1005/600/200'
    }
  }
})

HTML

<div id="app">
  <h2>Dynamic image in Vue.js:</h2>
  <p v-if="userProfilePic"><img style="width:100%" :src="userProfilePic" alt=""></p>
  <p><a href="#" @click="getImage()">Get a dynamic image</a></p>
</div>

The result

If you find this post useful, please let me know in the comments below and subscribe to my newsletter. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/bind-img-src-vue-js

PS: Make sure you check other Vue.js tutorials, e.g. redirect to login page in Vue.js.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment

3 Comments