LitElement-如果值为false,则不添加属性

有没有一种方法可以基本呈现这三种可能性:

<my-el someValue="a"></my-el>
<my-el someValue="b"></my-el>
<my-el></my-el> 

Note the explicit lack of the attribute someValue on the third.

为了正常渲染,我会这样做:

render() {
  const someValue = "a";

  return html`
    <my-el someValue=${someValue}></my-el>
  `;
}

But if someValue was undefined, it would render as <my-el someValue="undefined"></my-el> which I don't want.

有没有一种方法可以让虚假的人得到类似布尔的行为,但显示真实值的值呢?我阅读了文档,但希望我缺少一些东西。

The reason I want to do this is because I'd like to have a CSS selector that affects all of them that have [someValue] regardless of what the actual value is, but to not apply that if it isn't there.

P.S., I'm aware of workarounds like using :not([someValue=undefined]) or returning conditional HTML, so please don't reply with those. I'm using one of those right now, but if there is a direct answer to my question, hoping to swap out for that for a little cleaner code. Thanks.

评论
  • Jim
    Jim 回复

    You can simply use ifDefined directive for this. For AttributeParts, it sets the attribute if the someValue is defined and removes the attribute if the someValue is undefined. You can then further modify it using ternary operator to check for falsy values as well:

    import {ifDefined} from 'lit-html/directives/if-defined';
    
    return html`
       <my-el someValue=${ifDefined(someValue ? someValue : undefined)}></my-el>
    `;