2

我正在尝试使用 littemplate 从客户端调用服务器端函数。我检查了 Vaadin 站点上的示例,发现客户端可以通过 this.$server._some_method 调用服务器端。我尝试在 littemplate 中使用 $server,但在前端编译期间,vaadin 抛出错误,指出“属性 '$server' 在类型 'HelloWorld' 上不存在”。请让我知道这个程序有什么问题并指导我。谢谢你。

光照模板

import {LitElement, html} from 'lit-element';
import '@vaadin/vaadin-button/vaadin-button.js';

class HelloWorld extends LitElement {
    render() {
        return html`
            <div>
               <vaadin-button id="helloButton">Click me!</vaadin-button>
            </div>`;
    }
    
    sayHello(){
        showNotification("Hello");
        this.$server.greet(); //Problematic statement.
    }
}

customElements.define('hello-world', HelloWorld);

爪哇

package com.example.application.littemplate;

import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.littemplate.LitTemplate;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.template.Id;
import com.vaadin.flow.component.textfield.TextField;


//HelloWorld.java
@Tag("hello-world")
@JsModule("./views/littemplate/hello-world.ts")
public class HelloWorld extends LitTemplate {

@Id
// Uses the vaadin-button id "helloButton"
private Button helloButton;

public HelloWorld() {
   helloButton.addClickListener(event -> Notification.show("Hello " + nameField.getValue()));

}

@ClientCallable
    public void greet() {
        System.out.println("Hello server");
    }

}
4

1 回答 1

4

Typescript 不知道 LitTemplate 有一个$server变量。你必须自己定义它。您可以使用类型any或定义您的界面。例如:

private $server?: MyTestComponentServerInterface;

并添加@ClientCallable功能:

    interface MyTestComponentServerInterface {
        greet(): void;
    }

在您的情况下,您的打字稿可能是:

import {LitElement, html} from 'lit-element';
import '@vaadin/vaadin-button/vaadin-button.js';

class HelloWorld extends LitElement {
    private $server?: HelloWorldServerInterface;
    render() {
        return html`
            <div>
               <vaadin-button id="helloButton">Click me!</vaadin-button>
            </div>`;
    }
    
    sayHello(){
        showNotification("Hello");
        this.$server!.greet(); // should work with autocompletion
    }
}
interface HelloWorldServerInterface {
   greet(): void;
}
customElements.define('hello-world', HelloWorld);
于 2021-06-17T17:26:30.083 回答