Polymer:帮助使用dom-if

时间:2017-04-04 10:11:07

标签: polymer polymer-1.0 polymer-starter-kit

dom-if 在给定代码中不起作用!代码正在处理,在调试时它也返回true。但模板没有显示!!

为什么模板没有显示.. ??

<template is="dom-repeat" items="[[persistedProducts]]" as="product">
  <template is="dom-if" if="{{isProductLiked(product)}}">
    <paper-button on-click="dislikeThisProduct" 
      title="Click to UnLike" class="title-rose">
      <iron-icon icon="icons:thumb-up" class="title-rose" style="width:28px; height:17px;"></iron-icon>
      Liked
    </paper-button>
  </template>
</template>

isProductLiked: function(product) {
  let uid = this.user.uid;

  //Add visitor/user details here..
  this.$.queryProductLikes.disabled = false;
  this.$.queryProductLikes.ref.child(product.$key).child(uid).on("value", function(snapshot) {
    if(snapshot.val() != null) {
      //Display Like - if Liked.
      if(snapshot.val().isLiked) {
        return true;
      }
      return false;
    } else {
      //Not Liked
      return false;
    }
  });
}

1 个答案:

答案 0 :(得分:4)

我认为问题出在isProductLiked函数:

this.$.queryProductLikes.ref.child(product.$key).child(uid).on("value", function(snapshot) {
  if (snapshot.val() != null) {
    if (snapshot.val().isLiked) {
      return true;
    }
    return false;
  } else {
    return false;
  }
});

你在这里使用匿名函数(... function(snapshot) { ...),所以当你返回truefalse时,你没有返回isProductLiked函数,而是匿名功能

修改

我对Firebase不熟悉,因此这些可能有效,也可能无效:

可能的解决方案#1

  1. isProductLiked函数之外查询产品。
  2. 根据结果设置属性。 (让我们称之为productLikes这个例子)
  3. dom-if中使用此结果:<template is="dom-if" if="{{isProductLiked(product, productLikes)}}">
  4. 修改isProductLiked函数以包含productLikes参数并处理新逻辑。
  5. 这里的想法是,从isProductLiked函数中删除任何异步函数调用。

    可能的解决方案#2

    重新设计数据存储和查询,因此persistedProducts也包含这些内容。所以你可以这样写dom-if<template is="dom-if" if="{{product.isLiked}}">