我正在使用 vaadin 和 lit 实现一个复选框组件。我已经根据 vaadin 文档实现了它,但是我没有看到分组的复选框。
在控制台调试时,先调用“render()”,再调用“firstUpdated()”。所以我知道属性值将是一个空数组。
但是,即使我像示例一样实现它,我也不明白为什么会发生这种情况。如何正确实施?
这是自定义元素。
import { customElement, state } from 'lit/decorators.js';
import { html, LitElement } from 'lit';
import '@vaadin/vaadin-ordered-layout/vaadin-vertical-layout';
import '@vaadin/vaadin-checkbox/vaadin-checkbox-group'
import '@vaadin/vaadin-checkbox/vaadin-checkbox'
import { CheckboxElement } from '@vaadin/vaadin-checkbox';
import { Person } from '../../util/person';
import { getPeople } from '../../util/personUtil';
@customElement('checkbox-indeterminate')
export class CheckboxIndeterminate extends LitElement {
@state()
private items: Person[] = [];
@state()
private selectedIds: string[] = [];
async firstUpdated() {
this.items = await getPeople();
this.selectedIds = [String(this.items[0].id), String(this.items[2].id)];
console.log(`firstUpdated: ${JSON.stringify(this.items)}`);
console.log(`firstUpdated: ${JSON.stringify(this.selectedIds)}`);
}
render() {
console.log(`render: ${JSON.stringify(this.items)}`);
console.log(`render: ${JSON.stringify(this.selectedIds)}`);
return html`
<vaadin-vertical-layout theme="spacing">
<vaadin-checkbox
.checked="${this.selectedIds.length === this.items.length}"
.indeterminate="${this.selectedIds.length > 0 && this.selectedIds.length < this.items.length}"
@change="${(e: Event) =>
(this.selectedIds = (e.target as CheckboxElement).checked
? this.items.map((person) => String(person.id))
: [])}"
>
Notify users
</vaadin-checkbox>
<vaadin-checkbox-group
label="Users to notify"
theme="vertical"
.value="${this.selectedIds}"
@value-changed="${(e: CustomEvent) => (this.selectedIds = e.detail.value)}"
>
${this.items.map((person) => {
return html`
<vaadin-checkbox .value="${String(person.id)}">
${person.firstName} ${person.lastName}
</vaadin-checkbox>
`;
})}
</vaadin-checkbox-group>
</vaadin-vertical-layout>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'checkbox-indeterminate': CheckboxIndeterminate;
}
}
这是getPeople()
方法。
import { Person } from './person';
export async function getPeople(): Promise<Person[]> {
return [
new Person(1, "Aria", "Bailey"),
new Person(2, "Aaliyah", "Butler"),
new Person(3, "Eleanor", "Price")
]
}
这是Person
课堂。
export class Person {
id: number;
firstName: string;
lastName: string;
constructor(id: number, firstName: string, lastName: string) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}