首页 文章

Polymer 2.0:通知并反映属性

提问于
浏览
3

我是这个框架的新手,很想看到一些有用而简单的通知和反映属性属性的例子 . 请保持示例简单或为您提供的任何代码添加说明 .

2 回答

  • 5

    Notify:

    可以设置为True | False . 假设你有 parent-elementchild-element . 工作实例

    父母element.html:

    <dom-module id="parent-element">
      <template>
        <child-element foo="{{test}}"></child-element>
      </template>
    
      <script>
        Polymer({
          is: "parent-element",
          properties: {
            test: {
              value: "bar"
            }
          }
        })
      </script>
    </dom-module>
    

    如您所见,我们有一个名为 test 的属性,它传播到子元素,我们可以在其中进行操作 .

    儿童element.html:

    <dom-module id="child-element">
      <template>
        <paper-input value="{{test}}"></paper-input>
      </template>
    
      <script>
        Polymer({
          is: 'child-element',
    
          properties: {
            test: {
    
            }
          },
        });
      </script>
    </dom-module>
    

    什么是hapenning?在子元素中,我们定义了 test 属性,并且此属性绑定到 paper-input ,这意味着,只要我们在 paper-input 中写入内容,该属性就会自动更新 . 是的,'s awesome, we don'需要注意更新 child-element 内的属性,但父怎么可以知道属性 test 已经改变了?好吧,他不能 .

    这里来了 notify: true . 如果你设置它,你不必关心通知 parent-elementchild-elementtest 属性中的某个地方已被更改 .

    不久, parent-elementchild-element 中的属性 test 将同时更新

    Reflect-to-attribute:

    如名称所示,当您将其设置为某个属性时,它的值将在host元素的属性中可见 . 最好在一些例子中展示这一点 .

    Polymer 我们知道,设置一些绑定到某个元素的属性需要 $ 符号 .

    <custom-elem foo-attribute$="[[someProperty]]"></custom-elem>
    

    嗯,这可以说't be used everywhere. Let'在 custom-elem 内需要 foo-attribute .

    因为 foo-attribute 被声明为属性而不是属性,所以's value won'在元素内部是可见的 . 所以我们需要一些属性代表属性和属性的东西 .

    所以一些实际的例子,有一些真实的情况就像:

    <dom-module id='parent-element'>
      <template>
        <style>
           child-elemet[foo='bar'] {background-color: green}
           child-element[foo='foo'] {background-color: red}
        </style>
        <child-element foo="{{test}}"></child-element>
      </template>
    
      <script>
        Polymer({
          is: "parent-element",
          properties: {
            test: {
              value: "bar"
            }
          }
        })
      </script>
    </dom-module>
    

    在这种情况下,CSS将不起作用,因为 foo 是属性(不是属性),CSS仅应用于属性 .

    为了使它工作,我们必须在 child-element 内的 foo 属性上添加 reflectToAttribute .

    <dom-module id='child-element'>
      <template>
        <div>[[foo]]</div>
      </template>
    
      <script>
        Polymer({
          is: "child-element",
          properties: {
            foo: {
              reflectToAttribute: true
            }
          }
        })
      </script>
    </dom-module>
    

    在此之后, foo 将成为属性和属性 . 此时,CSS将应用于 child-element ,我们将能够在 child-element 内使用 foo 的值

  • 2

    来自文档:https://www.polymer-project.org/1.0/docs/devguide/data-binding

    要绑定到属性,请在属性名称后添加美元符号($):<div style $ =“color:{};”>双向绑定...属性必须设置为notify:true .

相关问题