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: ''
<div id="app">
  <img :src="image" style="width:100%;" alt="">

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 = ''


<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>

The result

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

Want to share this with your friends?

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