javascript - Aurelia 中的图像源绑定(bind)

标签 javascript webpack aurelia

我想在 aurelia 组件中绑定(bind) img 标签的 src 属性,我该怎么做?

我正在以这种方式在 reapeat.for 循环中创建一些图像:

<img repeat.for="picture of infoboard.memberPictures" src.bind="picture">

其中,memberPictures数组来自 View 模型,picture的值是一个相对地址:../../../assets/pictures/img_avatar.png.

在 View 模型中,我从数据库中获取成员的信息并通过处理数据,以这种方式填充 memberPictures 数组:

this.httpClient.fetch(`boards/membersof/${this.infoboard.id}`)
      .then(response => response.json())
      .then(data => {
        this.infoboard.memberPictures = data.result.map(element => `../../../assets/pictures/${element.profile_pic}.png`);
      });

这样绑定(bind)地址,图片不会加载,像这样:

picture of the problem

并且浏览器控制台显示以下错误:

img_avatar.png:1 GET http://localhost:8080/assets/pictures/img_avatar.png 404 (Not Found)

查看元素时,成员(member)头像的图片标签是这样的:

<img src.bind="picture" class="au-target" au-target-id="10" src="../../../assets/pictures/img_avatar.png">

但是如果我们向图片源提供静态图片,其地址与上例中生成的地址完全相同,如下所示:

<img repeat.for="picture of infoboard.memberPictures" src.bind="../../../assets/pictures/img_avatar.png">

不会有问题的:

picture of the problem

现在通过检查元素有不同的结果:

<img src="/a5e81f19cf2c587876fd1bb08ae0249f.png">

显然,aurelia 中处理静态文件的方式有所不同。图片源是怎么改成这样的,正确的绑定(bind)图片源的方式是什么?

最佳答案

这是因为您正在使用 webpack 来打包您的项目。

webpack 所做的其中一件事是将所有静态文件(图像、字体等)打包到包中——然后用指向包中相同 Assets 的不同“url”替换所有静态引用.

在运行时,您无权访问 bundle 之外的内容。

顺便说一句,这就是为什么我们需要对所有 aurelia 组件使用 PLATFORM.moduleName(),因为默认情况下 webpack 不会选择这些组件。

在您的例子中,您将 img 标签绑定(bind)到动态 url。 Webpack 无法将它们捆绑到输出包中,因为这些 url 是在运行时生成的。

您需要使用 require这个关键字在运行时工作 对于这样的目录结构:

directory structure

export class App {
  public urls:string[] = ["test", "t1", "t2", "t3"];

  getUrl(name)
  {
    return require(`./assets/${name}.png`);
  }
}
<template>
  <img repeat.for="url of urls" src.bind="getUrl(url)">
</template>

编辑:

在您的情况下,只需使用:

this.httpClient.fetch(`boards/membersof/${this.infoboard.id}`)
      .then(response => response.json())
      .then(data => {
        this.infoboard.memberPictures = data.result.map(element => require(`../../../assets/pictures/${element.profile_pic}.png`));
      });

关于javascript - Aurelia 中的图像源绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57347995/

相关文章:

javascript - 单击“浏览”按钮更改默认窗口位置

javascript - 简单的 Angular.js : ng-repeat not showing data

javascript - jspm 找不到 Aurelia 应用程序的 'feature' 插件的全局资源

vue.js - Vuejs 3 - vitejs 中 require.context 的替代方案是什么

Aurelia 使用 HEAD 方法获取客户端

view - Aurelia - 直通路线

javascript - 发布到 MySpace 的链接不起作用

java - youtube.subscriptions.list (api v3) - nextPageToken 不可用

angular - 在 ASP.NET Core 2.1 SPA 模板中找不到 webpack.config.js 或 webpack.config.vendor.js

npm - 未满足的对等依赖 webpack@3.6.0