使用 Web 组件中定义的函数

Using functions defined within web component

我已经构建了我的 Web 组件 DataUint 并为其分配了一个标签 <data-uint>,如下所示:

class DataUint extends HTMLElement
{
   ...
   set value(x) { ... }
   ...
}

customElements.define("data-uint", DataUint);

当创建和访问这样的组件时:

x = document.createElement('data-uint');
x.value = 10;

value的调用确实调用了setter方法并执行了它的功能。

然而,当我在 html 代码中内置我的组件时:

<body>
   <data-uint id='num'></data-uint>
</body>

并尝试 access/use 像这样:

x = body.children[0];
x.value = 10;

value 的调用为 x 引用的元素设置了一个新的 属性,但从未调用 Web 组件的 setter 方法。 然而 x 指的是我通过调用其他标准 Element 方法验证的页面(我的组件)上的正确元素。看起来这个访问方法正在返回一个通用的 Element 忽略特殊化。

问题:

我想我在这里遗漏了一些基本概念。如何以允许我使用其成员函数的方式从 JavaScript 访问 html 定义的组件?

您可能在定义组件之前执行 x = body.children[0]; x.value = 10;。另请注意,除非您在该代码运行之前声明了局部变量 body,否则 body 将是 undefined 并且您可能打算使用 const x = document.body.children[0];.

添加这行代码:

const x = document.body.children[0]; 
console.log(x.constructor.name);
x.value = 10;

如果这给你 HTMLElement,你的组件当时没有定义。如果还没有定义,就没有setter执行。

要检查,您也可以console.log(x.matches(':defined'));

要解决这个问题,请将您的代码包装在 DOMContentLoaded 侦听器中,或者等待定义组件:

customElements
  .whenDefined('data-uint')
  .then((promise) => {
    const x = document.body.children[0]; 
    console.log(x.constructor.name);
    x.value = 10;
  });