首页 > 解决方案 > 如何切换 LitElement Web 组件中的类

问题描述

我正在使用预编译的样式表(来自 SASS),只需要切换类。我有两个将写入事件的元素。基于事件是真/假,我想在我的组件上切换一个类。

这会起作用吗:

import { LitElement, html } from 'lit-element'
/**
 *
 *
 * @export
 * @class MenuMainButton
 * @extends {LitElement}
 */
export class MenuMainButton extends LitElement {
  static get properties() {
    return {
      name: { type: String },
      toggled: { type: String }
    }
  }

  constructor() {
    super()
    this.name = 'Menu'
    this.toggled = ''
    this.addEventListener('toggle-main-menu', this.handleEvents)
  }

  render() {
    return html`
      <a @click=${this._onClick} class="menu-button wk-app-menu-button app-menu-open ${this.toggled} govuk-body"
        >${this.name}</a
      >
    `
  }

  handleEvents(event) {
    this.toggled = event.toggle ? 'hide-item' : ''
  }

  _onClick() {
    const toggleMainMenu = new CustomEvent('toggle-main-menu', {
      toggle: this.toggled === '' ? 1 : 0
    })
    this.dispatchEvent(toggleMainMenu)
  }
}

window.customElements.define('main-menu-button', MenuMainButton)

标签: web-componentlit-element

解决方案


使样式动态化的一种方法是将绑定添加到模板中的类或样式属性。lit-html 库提供了两个指令,classMap 和 styleMap,可以方便地在 HTML 模板中应用类和样式。

样式 - LitElement


推荐阅读