web-component - 如何切换 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)
解决方案
使样式动态化的一种方法是将绑定添加到模板中的类或样式属性。lit-html 库提供了两个指令,classMap 和 styleMap,可以方便地在 HTML 模板中应用类和样式。
推荐阅读
- javascript - 为什么 RxJS subscribe 允许省略箭头函数和下面的方法参数?
- mysql - SQL将多个字段条件绑定为AND子句
- python - Python:在字典项中引用不同的字典项
- vb.net - 我应该避免错误“变量'foo'在被赋值之前被使用。'?
- electron - 如何为 Wayland 运行电子应用程序?
- angular - Angular bypassSecurityTrustResourceUrl 没有按预期工作
- angular - 如何使用 NgIdleKeepaliveModule 在构造函数中防止登录组件中的会话超时
- javascript - Node js - 如果记录已经存在,则添加序号后缀
- python - 将时间戳字符串日期转换为日期时间 python
- amcharts - AmCharts - XYChart - 最小柱高度