在聚合物中使用dom-if

问题描述 投票:1回答:1

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;
    }
  });
}
polymer polymer-1.0 polymer-starter-kit
1个回答
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参数并处理新的逻辑。

这里的想法是,从isProductLiked函数中删除任何异步函数调用。

可能的解决方案#2

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

© www.soinside.com 2019 - 2024. All rights reserved.