【问题标题】:Polymer 1.0 Data Binding in <styles><styles> 中的 Polymer 1.0 数据绑定
【发布时间】:2015-08-22 06:42:28
【问题描述】:

我又在修补 Polymer,我想做一些事情,但它不起作用,而且解决方法看起来很混乱。我想为元素设置样式,但要利用数据绑定。基本上我尝试这样做:

<dom-module id="proto-element">
  <template>
    <style>
      #wrapper{
        width:{{pixels}};
        background: #e1e1e1;
      }
      #bar{
        width:80%;
      }
    </style>
   <div id="wrapper">
     <div id="bar" style$={{barStyle}}>I'm the bar! <b>{{test}}</b></div>
   </div>
  </template>
</dom-module>

<script>
Polymer({
  is: "proto-element",
  ready: function() {
    this.pixels = "300px";
    this.test = "Fear me!"
  }
});
</script>

绑定到 this.test 的文本完美无缺。但是样式内部的小胡子标签会被忽略。有一个简单的解决方案吗?因为当您使用多个 css 规则时,使用内联样式 $= 语法非常混乱,而且如果您想要的值是在其他地方获得的,您总是需要连接一个字符串才能使其工作。对一个干净的解决方案有什么想法吗?

【问题讨论】:

    标签: html data-binding polymer


    【解决方案1】:

    恐怕您想要的(至少目前)是不可能的。数据绑定只能在

    在

    标签内不支持字符串连接,标签不能包含任何空格...

    tl;dr: 有两个问题会阻止您实现您想要的:1) 数据绑定仅适用于模板标签和 2 ) 如果你想打印出数据绑定的属性,它们必须包含在一个 html 标记中。

    您可以尝试不同的方法:

    ready: function () {
        this.$.wrapper.style.width = '300px';
    }
    

    this.$ 允许您轻松访问具有 id 属性的任何 DOM 元素(例如您的 #wrapper,它以 this.$. 的形式访问wrapper),然后您可以设置元素的任何其他属性(在本例中为 this.$.wrapper.style.width)。


    编辑:另外,我刚刚注意到您实际上已将

    <dom-module>
        <style> ... </style>
        <template> ... </template>
    </dom-module>
    <script> ... </script>
    

    查看Overview 和Migration guide。


    编辑 2:从 Polymer 1.1 开始,建议的元素结构(如 Max Waterman 所指出的)已更新为:

    <dom-module>
        <template> 
            <style> ... </style>
            ...
        </template>
        <script> ... </script>
    </dom-module>
    

    【讨论】:

    • 根据当前的聚合物文档,上面引用的建议是不正确的——事实上,恰恰相反:polymer-project.org/1.0/docs/devguide/styling.html "注意:在聚合物 1.1 之前,建议是放置
    • 感谢您指出,我已更新答案以反映新建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多