簡體   English   中英

在 Polymer 中使用 dom-if

[英]Using dom-if in Polymer

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;
    }
  });
}

我認為問題出在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包含likes。 所以你可以這樣寫dom-if<template is="dom-if" if="{{product.isLiked}}">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM