我想创建一个下拉菜单,并在单击输入时显示该菜单,其中带有一个用于删除或放置“隐藏”类的切换开关
我有这种方法
toggleMenu() {
this.classList.toggle("hidden");
}
这里是模板。
render(){
return html`
<input @click="${this.toggleMenu}" type="button">
<ul class="hidden">
<slot></slot>
</ul>
`;
}
答案 0 :(得分:4)
一种简单的解决方案是将属性添加到您的自定义元素,例如open
,可以在您的toggleMenu
方法中进行切换:
static get properties() {
return {
open: { type: Boolean },
};
}
constructor() {
super();
this.open = false;
}
toggleMenu() {
this.open = !this.open;
}
然后在您的render
方法中,根据<ul>
的值设置class
的{{1}}属性:
this.open
您可以在下面的代码段中看到此功能:
render(){
return html`
<button @click=${this.toggleMenu} type="button">Toggle</button>
<ul class=${this.open ? '' : 'hidden'}>
<slot></slot>
</ul>
`;
}
// import { LitElement, css, html } from 'lit-element';
const { LitElement, css, html } = litElement;
class DropDownMenu extends LitElement {
static get properties() {
return {
open: { type: Boolean },
};
}
static get styles() {
return css`
ul.hidden {
display: none;
}
`;
}
constructor() {
super();
this.open = false;
}
toggleMenu() {
this.open = !this.open;
}
render(){
return html`
<button @click=${this.toggleMenu} type="button">Toggle</button>
<ul class=${this.open ? '' : 'hidden'}>
<slot></slot>
</ul>
`;
}
}
customElements.define('drop-down-menu', DropDownMenu);
如果要将其他类应用于<script src="https://bundle.run/lit-element@2.2.1"></script>
<drop-down-menu>
<li>Item 1</li>
<li>Item 2</li>
</drop-down-menu>
,则需要按照in the LitElement docs的说明研究<ul>
函数。
或者,您可以在classMap
属性声明中添加reflect: true
,这样您就可以单独使用CSS来显示或隐藏open
,而不必在{ {1}}:
<ul>
这里是有效的代码段:
class
render
这两种都是常见的方法,最适合您的应用程序的方法将取决于您的用例和个人喜好。