2017-04-18 15 views
0

私は<template is="dom-if" if=...を論理条件で使いたいと思っています。<template is = "dom-if"を条件付きで使用する

私がしようと、任意の結合がtruthyように表示されます。

<link href="https://polygit.org/components/polymer/polymer.html" rel="import"> 
 

 
<dom-module id="test-thing"> 
 
    <template> 
 
    <template is="dom-if" if="{{title == 'foo'}}" restamp> 
 
     Title is <b>FOO</b> 
 
    </template> 
 
    <template is="dom-if" if="{{title}} == 'bar'" restamp> 
 
     Title is <b>BAR</b> 
 
    </template> 
 
    
 
    Actual: "{{title}}" 
 
    </template> 
 
    <script> 
 
    Polymer({ 
 
     is: 'test-thing', 
 
     properties: { 
 
     title: {type: String,value:''} 
 
     } 
 
    }); 
 
    </script> 
 
</dom-module> 
 

 
<div> 
 
    Title: foo<br> 
 
    <test-thing title="foo"></test-thing> 
 
</div> 
 
<div> 
 
    Title: bar<br> 
 
    <test-thing title="bar"></test-thing> 
 
</div> 
 
<div> 
 
    Title: abc<br> 
 
    <test-thing title="abc"></test-thing> 
 
</div>

dom-iftemplateからif条件を適用する正しい方法は何ですか?

答えて

7

あなたの機能を定義する必要があります。

スクリプト内
<template is="dom-if" if="{{_isEqualTo(title, 'Foo')}}"> 

、その後:

function _isEqualTo(title, string) { 
    return title == string; 
} 

プロパティtitleが変更されるたびに、機能_isEqualToが呼び出されます。あなたは不動産や何かを観察する必要はありません。

関数_isEuqalToは2つのパラメータで呼び出され、2つ目のパラメータは値を比較する単純な文字列です。

+0

おかげクバを - 私は関数内で条件をラップまたは関連するプロパティが変更されたときに設定されたプロパティを追加することができることを認識し、それは本当にだけです方法? 'if'ブロックが' if'を評価できるように関数を抽出するのは非常に厄介です。 – Keith

+0

他の方法はありません。プロパティの 'computed'オプションや' observer'オプションも使用できます。しかし、{{title == 'foo'}}のようなものはありません。あなたはそれに慣れなければなりません。私はポリマーの前にハンドルバーを使用していました。最初は私にとっては迷惑でした。 –

3

バインドで使用できる唯一のロジックはありません。例えば :

<template is="dom-if" if="{{_isEqualTo(title, 'Foo')}}"> 
<template is="dom-if" if="{{!_isEqualTo(title, 'Foo')}}"> 
0

あなたのデータはfooがブールたかの属性を持っていたようなものであった場合、その "フー":trueまたは "isFoo":真。次に、あなただけ行うことができます:

<template is="dom-if" if="{{isFoo}}"> 
    Foo 
</template> 
関連する問題