如何在 Vaadin 的另一个类中使用路由器布局类的变量/方法? [英] How to use variables/methods of router layout class in another class in Vaadin?
问题描述
我使用的是 Vaadin 14.0.3.我有一个带有方法 someCode
的类 MainLayout
.我使用这个类作为另一个名为 MainView
的类的布局.是否可以在MainView
中使用someCode
方法?示例如下:
I am using Vaadin 14.0.3. I have a class MainLayout
with a method someCode
. I am using this class as layout for another class named MainView
. Is it possible to use the method someCode
in MainView
? Here's the example:
public class MainLayout {
public void someCode() {
}
}
@Route(value = "main", layout = MainLayout.class)
public class MainView {
}
谢谢!
推荐答案
在我的应用程序中,我使用 Erik 的回答中描述的方法(在路由视图的 onAttach
期间获取父组件).但是我对其进行了一些扩展并利用接口来防止重复代码.这是我的设置:
In my application I use the approach described in Erik's answer (get the parent component during onAttach
of the routed view). However I expanded it a bit and make use of interfaces to prevent duplicate code. Here's my setup:
public class MainView extends HorizontalLayout implements RouterLayout {
public MainView(){
...
}
public interface Retriever extends HasElement {
default MainView getMainView() {
Component parent = getElement().getComponent().orElse(null);
while (parent != null && !parent.getClass().equals(MainView.class)) {
parent = parent.getParent().orElse(null);
}
return (MainView)parent;
}
}
}
@Route("main")
public class MainRoute extends VerticalLayout implements MainView.Retriever {
public MainRoute(){
...
}
@Override
public void onAttach(){
MainView mainView = getMainView();
if (mainView != null){
mainView.someCode(); // do with the mainView what you want here
} else {
LOGGER.error(...);
}
}
}
请注意,我的 routerLayout 被称为 MainView 而不是 MainLayout.我不想更改该名称,因为名称MainView"用于大多数官方文档和示例中的路由器布局
这篇关于如何在 Vaadin 的另一个类中使用路由器布局类的变量/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!