【问题标题】:show div on button click with Lit component使用 Lit 组件单击按钮时显示 div
【发布时间】:2022-10-20 23:58:14
【问题描述】:

我有一个 Lit 组件。所以目标是当按钮被点击时,我想显示一个带有模式弹出窗口的 div。我怎样才能做到这一点?这是我的代码:

    import {LitElement, html, css} from 'lit';
    import {customElement, property} from 'lit/decorators.js';

    @customElement('my-form')
    export class CustomForm extends LitElement {

      @property()
 
      render() {
        return html`
        <div>
          <button @click="${this.showModalForm}">Open modal</button>
        </div>
        <div id="modalWindow" class="modalWindow"></div>
        `  
      }
    
      showModalForm() {
        console.log('clicked')
        
      }

    }

【问题讨论】:

  • 标准的 HTML <dialog> element 可能更容易
  • 请解释究竟是什么不工作,它是如何失败的,以及你所期望的。

标签: javascript components web-component lit


【解决方案1】:

尝试这个

    import {LitElement, html, css} from 'lit';
    import {customElement, property} from 'lit/decorators.js';

    @customElement('my-form')
    export class CustomForm extends LitElement {

     static styles = css`
        .hide { display: none }
     `;

      render() {
        return html`
        <div>
          <button @click="${this.showModalForm}">Open modal</button>
        </div>
        <div id="modalWindow" class="modalWindow hide"></div>
        `  
      }
    
      showModalForm() {
        this.renderRoot.querySelector('#modalWindow').classList.toggle("hide");
      }

    }

【讨论】:

    【解决方案2】:

    我在 vanilla js 中添加解决方案。

    import { LitElement, html, css } from "lit";
    import { when } from "lit/directives/when.js";
    
    export class CustomForm extends LitElement {
        static properties = {
            showModalForm: { type: Boolean },
        };
    
        constructor() {
            this.showModalForm = false;
        }
    
        render() {
            return html`
                <div>
                    <button @click="${() => (this.showModalForm = true)}">Open modal</button>
                </div>
                <!-- solution 1 : modal don't added in dom tree until click, lit will create later -->
                ${when(this.showModalForm, () => html`<div id="modalWindow" class="modalWindow"></div>`)}
                <!-- solution 2 : modal added in dom tree but hidden -->
                <div id="modalWindow" class="modalWindow" ?hidden=${!this.showModalForm}></div>
            `;
        }
       }
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2013-01-16
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多