在 Polymer 元素中设置 <img> 的 src。

4
以下是我的聚合元素的代码。我已经尝试了正常的dom绑定,一切都很顺利。然而,img的src却不起作用。我在chrome开发工具中检查了html,显示的src都是错误的。这里的src说的是/img/12.jpg,这意味着图像在html文件所在的文件夹中,但它实际上指的是文件夹的根目录。我期望在开发工具中看到的src是 http://localhost:3000/elements/image-hover/img/12.jpg,但实际上是img/12.jpg。除了将其硬编码为预期的src之外,我能做什么?
<dom-module id="image-hover">
             <template>
                <img src="{{imgsrc}}"/>
             </template>
        </dom-module>
        <script>
          (function() {
            Polymer({
              is: 'image-hover',

              properties: {
                imgsrc: {
                    type: String,
                    value: 'img/12.jpg'
                }
              }
          });
          })();
       </script>

编辑:我通过使用Polymer提供的content标签解决了这个问题。
<content id="image" select="img"></content>

这个问题仍然存在,我如何找到该元素所在文件夹的来源。
2个回答

5
您可以执行以下操作:
<dom-module id="image-hover">
    <template>
        <img src="{{imgsrc}}"/>
    </template>
</dom-module>
<script>
    Polymer({
        is: 'image-hover',

        properties: {
            imgsrc: {
                type: String,
                value: function () {
                    return location.host + "/img/12.jpg";
                }
            }
        }
    });
</script>
value现在是一个返回使用位置对象的String的函数。有关此信息的更多信息可以在这里找到。简单地说,它包含有关当前URL的信息。

在我的情况下,location.host返回的是localhost:3000,而不是localhost:3000/elements/image-hover。 - TMess
你尝试过这样写吗?value: function () { return "/image/12.jpg"; } - Ben Thomas
不起作用,而且我认为它不应该...路径是 /elements/img/12.jpg即便如此,我不想要一个硬编码的解决方案... 更多是通用的。 - TMess

4
您可以按照以下方式使用 this.resolveUrl 方法:
          properties: {
            imgsrc: {
                type: String,
                value: function() {return this.resolveUrl('img/12.jpg')}
            }
          }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接