使用 Element API

本节介绍如何使用 Element API 和单一 DOM 元素创建一个组件。

import com.vaadin.flow.component.AbstractSinglePropertyField;
import com.vaadin.flow.component.Synchronize;
import com.vaadin.flow.component.Tag;

@Tag("input") (1)
public class ColorPicker extends AbstractSinglePropertyField<ColorPicker, String> { (2)

    public ColorPicker() {
        super("value", "", false); (3)

        getElement().setAttribute("type", "color"); (4)

        setSynchronizedEvent("change"); (5)
    }

}
1 定义由 Component` 类自动创建的 元素,可以通过 getElement() 方法访问。
2 使用 AbstractSinglePropertyField 作为基类,该类适合创建基于单一元素属性的组件。
3 传入表示组件值的元素属性名称。
4 设置 type 属性的值。
5 默认情况下,AbstractSinglePropertyField 监听 value-changed 事件,但是 <input type=color> 触发 change 事件。

组件实现完成后,可以在视图中使用,示例:

@Autowired
private Notifications notifications;

@Subscribe
public void onInit(final InitEvent event) {
    ColorPicker colorPicker = new ColorPicker();
    getContent().add(colorPicker);

    colorPicker.addValueChangeListener(e ->
            notifications.show("Color: " + e.getValue()));
}
color picker