【问题标题】:Why getElement().getProperty("value") not working为什么 getElement().getProperty("value") 不起作用
【发布时间】:2021-06-21 09:42:02
【问题描述】:

我在读取 Web 组件中的属性时遇到问题。我不明白为什么它不起作用。我创建了一个简单的例子,点击按钮后我应该得到属性的值,但它是空的。我不知道为什么?在我的其他测试中,setProperty 工作正常,但是 getProperty 总是获得与我在 setProperty 中设置的值相同的值。我也尝试在浏览器中更改属性。 PropertyChangeListener 在客户端更改值后也永远不会触发。为此花很多时间。谁能告诉我发生了什么?

HelloWorld.class

import com.vaadin.flow.component.DomEvent;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.littemplate.LitTemplate;

@Tag("hello-world")
@JsModule("./components/hello-world.ts")
public class HelloWorld extends LitTemplate {
    @DomEvent("click")
    public static class ClickEvent extends ComponentEvent<HelloWorld> {
        public ClickEvent(HelloWorld source, boolean fromClient) {
            super(source, fromClient);
        }
    }

    public HelloWorld() {
        setId("hello-world");
        getElement().addPropertyChangeListener("value", "change", e -> {
            System.out.println("change value: " + e.getValue());
        });
        addListener(ClickEvent.class, e -> System.out.println("getValue(): " + getValue()));
    }
    public void setValue(String value) {
        getElement().setProperty("value", value);
    }

    public String getValue() {
        return getElement().getProperty("value");
    }
}

hello-world.ts

import { LitElement, html, property} from 'lit-element';

export class HelloWorld extends LitElement {
    @property({type: String}) value = 'unset';

    render() {
        return html`
            <div>${this.value}</div>
            <button @click=${this._click}>Button</button>
        `;
    }

    _click() {
        this.value = 'Clicked';
        let click = new Event('click');
        this.dispatchEvent(click);
    }
}
customElements.define("hello-world", HelloWorld);

【问题讨论】:

  • 你收到错误了吗?
  • 我没有任何错误

标签: java typescript vaadin vaadin-flow


【解决方案1】:

您已将属性值设置为在客户端触发change 事件时同步回服务器,但未触发此类事件。但是,有一个 click 事件,因此您可能需要更改 addPropertyChangeListener 以使用该 DOM 事件名称。

【讨论】:

  • 我不明白这个。每当属性“值”在客户端发生变化时,我应该将 dispatchEvent 发送到服务器吗?例如,我在客户端生成图像,但并不总是需要这些数据。
  • 服务器无法直接监控客户端属性。由您触发它以检查值是否已更改。您可以通过定义一个应该用作触发器的 DOM 事件来做到这一点。每当为元素分派具有该名称的 DOM 事件时(以编程方式或通过本地事件的用户操作),Flow 将检查属性值并将其发送到服务器,以防它与最后知道的服务器端值不同。
  • 好的,我明白了,但我认为这不是我的情况的最佳解决方案。我错误地理解它的方式和原因:addPropertyChangeListener。我认为应该更好地命名addPropertyChangeListener - 在方法信息的名称中缺少有关它用于客户端到服务器端之间同步的信息。我阅读了文档,但有一个非常简单的示例。在我的实际情况下,单击组件外部的按钮后,我需要从组件中读取值。
猜你喜欢
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
相关资源
最近更新 更多