【问题标题】:Vue.js How to concatenate a string with a method in img srcVue.js 如何将字符串与 img src 中的方法连接起来
【发布时间】:2021-09-02 01:45:45
【问题描述】:

这是我的 HTML:

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

这是脚本:

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

输出是替代文本,即使我得到了正确的路径 http://localhost:8080/@/assets/thumbsUp.png

【问题讨论】:

    标签: html vue.js vuejs2 axios


    【解决方案1】:

    imgUrl 必须是计算属性并使用 require 加载图像:

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

    和:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多