Vue.js How to concatenate a string with a method in img src

Viewed 108

So this is my HTML:

<img v-bind:src="'@/assets/'+imgUrl()+'.png'" alt="thumbs-Up" id="thumbsUp"> 

And this is the script:

import axios from 'axios'
export default {
    data(){
        return{
            status:''
        }
    },
    methods: {
        getStatus(){
            axios.get('/api/health')
            .then(response => this.status = response.data.status)
            .catch(err => console.log(err.message))
        },

        imgUrl(){
            if (this.status =='UP')
            return "thumbsUp"
            else
            return "thumbsDown"
        }
  }
}

The output is the alternative text, even if I got the right path http://localhost:8080/@/assets/thumbsUp.png

1 Answers

imgUrl has to be a computed property and use require to load the image :

<img v-bind:src="require('@/assets/'+imgUrl+'.png')" alt="thumbs-Up" id="thumbsUp"> 

and :

import axios from 'axios'
export default {
    data(){
        return{
            status:''
        }
    },
 computed:{
          imgUrl(){
               return this.status ==='UP'?"thumbsUp":"thumbsDown"
            }
        },
    methods: {
        getStatus(){
            axios.get('/api/health')
            .then(response => this.status = response.data.status)
            .catch(err => console.log(err.message))
        },
     
  }
}
Related