繁体   English   中英

dom-if与Polymer 1.x有关

[英]dom-if issue with Polymer 1.x

我在模板转发器中有几个有条件标记的元素。 现在,当我更新数据时,if条件似乎没有生效,这导致undefined传递到处理这些元素的数据的函数中。

使用restamp属性似乎没有帮助( https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-if )。 到目前为止,我只能通过在我的更改处理程序中清空items属性( this.items = []; )来解决此问题,该处理程序启动新请求。

这样可行,但在显示新数据之前,模板会在很短的时间内变空。 不一定是个问题,但我想知道我做错了什么。

以下是代码的相应部分:

<template>
...
<iron-ajax
  id="ironajax"
  url="https://www.url.com/api"
  params="{{ajaxParams}}"
  handle-as="json"
  on-response="handleResponse"
  on-error="handleError">
</iron-ajax>
...
<template is="dom-repeat" items="{{items}}" id="items">
...
<template is="dom-if" if="{{item.info.subtitle}}">: 
  <span>{{truncateSubtitle(item.info.subtitle)}}</span
</template>
...
Polymer({
  is: 'my-element',
  properties: {
    query: {
      type: String,
      value: ''
    }
    ...
    items: {
      type: Array,
      value: []
    }
  }
  ...
  handleChange: function() {
    if (this.value !== '') {
      this.items = [];
      this.query = this.value;
      this.$.ironajax.generateRequest();
    }
  }
...

给定"{{item.info.subtitle}}" ,如果item.infonullundefined或者如果item.info.subtitle undefined ,则绑定将不会刷新并且可能具有过时值(在重复的上下文中)节点被重用)。

Polymer不会对undefined值执行计算,因为它在很多情况下都是性能增强,但在这种情况下它可能很棘手。

您应该使用函数来解决正确的状态。 就像是

if="{{hasSubtitle(item)}}"

hasSubtitle function(item) {
  return item.info && item.info.subtitle;
}

“dom-if”的“if”属性需要布尔值。

如果“item.info.subtitle”不为空或为null,请尝试创建将设置为true或false的聚合物属性。

然后使用dom-if创建的属性:

<template is="dom-if" if="{{hasSubtitle}}" >

参考: http//polymer.github.io/polymer/ - > dom-if(下拉列表)


附加信息:6月10日添加

尝试使用属性而不是方法。

像这样声明你的财产:

Polymer({
    is: "my-element",
    properties: {
        hasSubtitle: {
            type: Boolean,
            value: 'false',  //false or true, the more common case.
        }
    },
    ...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM