littleX
littleX

Reputation: 25

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

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

Upvotes: 1

Views: 227

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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))
        },
     
  }
}

Upvotes: 1

Related Questions