将输入的值 属性 绑定到属性

Binding the value property of an input to an attribute

我尝试使用 Web 组件(通过验证和服务器通信)创建自己的自定义 DOM 元素。我正在遵循 MDN 上的教程:https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements

    attributeChangedCallback(name, oldValue, newValue) {
    console.log(newValue);
  }

我能够接收属性的更改。但是,如果我有一个文本框,值会发生变化。如何将文本框的值绑定到属性?这甚至是一个好方法吗?

这是我的代码:

'use strict';

class PopUpInfo extends HTMLElement {

    static get observedAttributes() {
        return ['value'];
    }
    constructor() {
      // Always call super first in constructor
      super();

      // write element functionality in here

    var shadow = this.attachShadow({mode: 'closed'});
    console.log("Created");
    let tbName = document.createElement("input");
    shadow.appendChild(tbName);
    }
    attributeChangedCallback(name, oldValue, newValue) {
        console.log(newValue);
      }
  }
  customElements.define('popup-info', PopUpInfo);

稍后,我想将多个 html 控件添加到 "PopUpInfo"。名称稍后会变成 "Controlunit".

您需要获取属性或 属性 并将该值传递到内部 DOM。除非您使用框架,否则没有 "binding"。如果您想使用 LitElement 或其他东西,那么您将获得绑定。我个人认为这些框架的开销很大。

但是看看这个例子:

class PopUpInfo extends HTMLElement {
  static get observedAttributes() {
    return ['value'];
  }
  constructor() {
    // Always call super first in constructor
    super();

    // write element functionality in here

    var shadow = this.attachShadow({mode: 'open'});
    let textEl = document.createElement("input");
    shadow.appendChild(textEl);
    
    // Set attribute to value of inner element `.value`
    textEl.addEventListener('input', (evt) => {
      this.setAttribute('value', textEl.value);
    });
  }
  
  attributeChangedCallback(name, oldValue, newValue) {
    console.log(`attributeChangedCallback(${name}, ${oldValue}, ${newValue})`);
    if (oldValue !== newValue) {
      this.value = newValue;
    }
  }
  
  get value() {
    let textEl = this.shadowRoot.querySelector("input");
    return textEl.value;
  }
        
  set value(newValue) {
    console.log(`set value(${newValue})`);
    let textEl = this.shadowRoot.querySelector("input");
    if (newValue == null) { // check for null and undefined           textEl.value = '';
    }
    else {
      textEl.value = newValue;
    }
  }
}

customElements.define('popup-info', PopUpInfo);
<popup-info value="my info"></popup-info>

首先:由于您只观察 一个 属性,因此您的 attributeChangedCallback 函数只需要查看 oldValuenewValue 是否不同。如果它们没有不同,那么就没有什么可做的。如果它们不同,则使用 newValue.

在我的示例中,我将属性的值传递给名为 value 的 属性。

在 属性 setter 中,我检查值是 null 还是 undefined (对 null 使用双等号(x == null) 就是这样做的。如果它是 nullundefined 那么我们将内部 <input> 元素的 value 设置为空字符串。如果它不是 nullundefined 然后我们将内部 <input> 元素的 value 设置为发送的任何内容。

属性 getter 只是读取内部 <input> 元素的 value 和 returns 那个。