Vue.js 如何将字符串与 img src 中的方法连接起来

Posted

技术标签:

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

这是我的 html

<img v-bind:src="'@/assets/'+imgUrl()+'.png'"  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

【问题讨论】:

【参考方案1】:

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

<img v-bind:src="require('@/assets/'+imgUrl+'.png')"  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))
        ,
     
  

【讨论】:

我可以给你反馈一下这篇文章吗? ***.com/questions/68020475/…

以上是关于Vue.js 如何将字符串与 img src 中的方法连接起来的主要内容,如果未能解决你的问题,请参考以下文章