聚合物数据变化不反映



我正在尝试隐藏/取消隐藏带有聚合物按钮的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元素根本不会被隐藏/取消隐藏。此外,在控制台上,我可以看到this.hide已更改为所需的值,但无论如何该元素都保持隐藏状态。我需要做什么/自动强制内容更新吗?为什么这不起作用?如何确保通过更改hide变量来隐藏px-card元素?

好问题。所以,首先我想强调一下,该聚合物组件的当前JS代码实际上并不是"非常聚合物",因此您以非常"jQuery的方式"与DOM交互,而不是使用Polymer库的所有优点。

我建议如何重写该代码:

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

因此,我们在这里添加了 1( 点击事件处理器hidePxCard2( 通过方括号从双向竞价切换到单向竞价[[hide]],因此,没有理由使用双向绑定。

然后,让我们调整js部分:

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

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

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

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

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

或在整个应用程序(页面(中设置为全局样式的某个位置。

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

确保要隐藏的内容具有样式,以便浏览器知道当hidden为 true 时该怎么做(即浏览器应将display设置为none(。 例如:

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

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

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

此代码示例演示了上述操作。

Web 组件最佳实践提供了有关使用:host选择器的详细信息。

最新更新