我想制作一个下拉菜单,当单击输入时,菜单会显示一个用于删除或放置“隐藏”类的切换开关
我有这个方法
toggleMenu() {
this.classList.toggle("hidden");
}
这里是模板。
render(){
return html`
<input @click="${this.toggleMenu}" type="button">
<ul class="hidden">
<slot></slot>
</ul>
`;
}
最佳答案
一个简单的解决方案是向自定义元素添加一个属性,例如open
,在您的 toggleMenu
中切换方法:
static get properties() {
return {
open: { type: Boolean },
};
}
constructor() {
super();
this.open = false;
}
toggleMenu() {
this.open = !this.open;
}
然后在你的render
中方法设置<ul>
的class
基于 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/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44282d306921282129212a3004766a766a75" rel="noreferrer noopener nofollow">[email protected]</a>"></script>
<drop-down-menu>
<li>Item 1</li>
<li>Item 2</li>
</drop-down-menu>
如果您想将其他类(class)应用于 <ul>
您需要查看 classMap
功能如所述in the LitElement docs .
或者,您可以添加 reflect: true
到open
属性声明,可让您显示或隐藏 <ul>
单独使用 CSS,而不是设置其 class
在render
:
static get properties() {
return {
open: {
type: Boolean,
reflect: true,
},
};
}
static get styles() {
return css`
ul {
display: none;
}
:host([open]) ul {
display: block;
}
`;
}
这是一个工作片段:
// import { LitElement, css, html } from 'lit-element';
const { LitElement, css, html } = litElement;
class DropDownMenu extends LitElement {
static get properties() {
return {
open: {
type: Boolean,
reflect: true,
},
};
}
static get styles() {
return css`
ul {
display: none;
}
:host([open]) ul {
display: block;
}
`;
}
constructor() {
super();
this.open = false;
}
toggleMenu() {
this.open = !this.open;
}
render(){
return html`
<button @click=${this.toggleMenu} type="button">Toggle</button>
<ul>
<slot></slot>
</ul>
`;
}
}
customElements.define('drop-down-menu', DropDownMenu);
<script src="https://bundle.run/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660a0f124b030a030b030812265448544857" rel="noreferrer noopener nofollow">[email protected]</a>"></script>
<drop-down-menu>
<li>Item 1</li>
<li>Item 2</li>
</drop-down-menu>
这两种方法都是常见的方法,最适合您的应用程序的方法将取决于您的用例和个人偏好。
关于javascript - 如何将事件传递给 LitElement 中的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759198/