Vue.js img src 连接变量和文本

Vue.js img src concatenate variable and text

我想将 Vue.js 变量与图像 URL 连接起来。

我计算的:

imgPreUrl : function() {
    if (androidBuild) return "android_asset/www/";
    else return "";
}

如果我为 android 构建:

<img src="/android_asset/www/img/logo.png">

其他

<img src="img/logo.png">

如何将计算变量与 URL 连接起来?

我试过了:

<img src="{{imgPreUrl}}img/logo.png">

您不能在属性中使用卷曲(小胡子标签)。使用以下内容连接数据:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

或简写:

<img :src="imgPreUrl + 'img/logo.png'">

阅读 Vue docs 中有关动态属性的更多信息。

在另一种情况下,我可以使用带有反引号的模板文字 ES6, 所以你的可以设置为:

<img v-bind:src="`${imgPreUrl()}img/logo.png`">

试试

<img :src="require(`${imgPreUrl}img/logo.png`)">

如果你从数据库中处理这个尝试:

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

对我来说,它说模块没有找到并且不工作。 最后,我找到了这个解决方案并成功了。

<img v-bind:src="require('@' + baseUrl + 'path/path' + obj.key +'.png')"/>

需要在本地路径的开头添加'@'。

如果有帮助,我正在使用以下方法获取头像:

<img
        :src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
        class="rounded-circle"
        :width="size"
    />

以下两种方法均有效。

方法一

连接 + 符号并用 single/double 引号包裹字符串。

<img :src="imgPreUrl() + 'img/logo.png'">

方法二

用反引号 ` 换行,用 ${variable} 换行变量。由于 imgPreUrl 是一种方法,因此,

<img :src="`${imgPreUrl()}img/logo.png`">