聚合物数据变化不反映

Polymer data change doesn't reflect

我试图在 Polymer 中 hide/unhide 一个带有按钮的 UI 元素,但它不起作用。我有按钮和元素:

<button id="runPredictionButton">
    <i>Button text</i>
</button>
<px-card 
hidden$="{{hide}}">    
//...content here
</px-card>
<div class="output"></div>          

我还定义了 属性 和事件侦听器:

  <script>
    Polymer({
      is: 'custom-view',
      properties: {
        hide: {
          type: Boolean,
          value: false 
        },
      },
    ready: function() {
      var self = this;
      this.$.runPredictionButton.addEventListener('click', function() {
        if (some_conditon == true) {
          filerootdiv.querySelector('.output').innerHTML = 'Is true';          
          this.hide = true
          console.log("This hide should be true:" + this.hide);
        } 
        else {
          filerootdiv.querySelector('.output').innerHTML = 'Is false';          
          this.hide = false
          console.log("This hide should be false:" + this.hide);
        }
      });
    }
  });      
  </script>

我确定 some_conditon 有效,因为 .output 元素的内容确实发生了变化,但是 px-card 元素根本没有得到 hidden/unhidden。此外,在控制台上我可以看到 this.hide 已更改为所需的值,但无论如何该元素都保持隐藏状态。有什么我需要 do/automatically 强制更新内容吗?为什么这不起作用?如何确保通过更改 hide 变量隐藏 px-card 元素?

也许 CSS 规则阻止它被隐藏?

确保您要隐藏的内容已设置样式,以便浏览器知道在 hidden 为真时要做什么(即,浏览器应将 display 设置为 none) .例如:

<style>
  :host{
    display: block;
  }
  :host[hidden]{
    display: none;
  }
</style>

要查看这是否真的是您问题的原因,您可以查看以下信息:

getComputedStyle(elementToHide).getPropertyValue("display"); 

This code sample shows the above in action

Web Components Best Practices 有更多关于使用 :host 选择器的信息。

好问题。因此,首先我想强调的是,该 Polymer 组件的当前 JS 代码实际上并不是 "very Polymer",因此您在非常 "jQuery way" 中与 DOM 交互,而不是全部使用Polymer 库的好处。

我建议如何重写该代码:

<button on-tap="hidePxCard">
    <i>Button text</i>
</button>
<px-card
hidden$="[[hide]]">
<!-- ...content here -->
</px-card>
<div class="output"></div>

所以,我们在这里添加了 1) on-tap 事件处理程序 hidePxCard 2) 通过方括号从 [[hide]] 的双向投标切换为单向投标,所以,有没有理由使用双向绑定。

然后调整js部分:

<script>
    Polymer({
        is: 'custom-view',
        properties: {
            hide: {
                type: Boolean,
                value: false
            }
        },
        hidePxCard: function() {
            this.set('hide', !this.hide);
        }
    });
</script>

您能看到现在的代码看起来多干净吗?我们只是在每个 hidePxCard 调用中设置一个 属性。我们的目标是,我们需要使用绑定到 html 属性的 Polymer 属性进行操作,而不是直接操作 DOM。所以,您的元素现在是数据驱动的。

此外,我假设当元素上存在 [hidden] 属性时,存在一些 CSS 代码来隐藏某些内容。

可以通过以下方式在 px-card 元素内完成:

<style>
    :host{
        display: block;
    }
    :host[hidden]{
        display: none;
    }
</style>

或已在应用程序(页面)的某处设置为全局样式。