如何在Dart中创建Web组件 2.1昆特的document.registerElement() 2.2用window.customElements.define()尝试相同的事情 2.3尝试使用JS Interop

问题描述

1。上下文

可以在香草JS中创建Web组件,方法是:

  1. 创建一个extends HTMLElement
  2. 的类
  3. 然后注册
    window.customElements.define('app-drawer',AppDrawer);
    

因为我在Dart中有很多代码,所以我想我可以用它来做到这一点。但是我遇到了一些障碍。 主要是以下事实:document.registerElement()已过时,window.customElements.define()似乎无效

我主要使用Microsoft Edge作为浏览器。但是无论如何它都使用铬。而且我也已经在Chrome上测试了下面提到的所有内容

2。我尝试过的

2.1。昆特的document.registerElement()

答案

Günter's answer指向this dartpad,后者使用document.registerElement()对其进行定义。

他的回答有用,但是不建议使用document.registerElement()

document.registerElement is deprecated and will be removed in M80,around February 2020. Please use window.customElements.define instead.

或者至少在我的计算机上它可以工作,因为他的DartPad实际上返回了错误NoSuchMethodError: method not found: 'registerElement'

2.2用window.customElements.define()尝试相同的事情

My DartPad

My Gist

import 'dart:html';

main() {
  try {
    window.customElements.define('graph-button',GraphButton);
    final GraphButton button = GraphButton();
    document.body.append(button);
    button.changeInnerHtml();
  } catch (e) {}
}

class GraphButton extends HtmlElement {
  static const String tag = 'graph-button';

  factory GraphButton() => Element.tag(GraphButton.tag);

  GraphButton.created() : super.created();

  changeInnerHtml() => innerHtml = 'foo';
}

上面的代码将产生以下错误消息:

Error: Failed to execute 'define' on 'CustomElementRegistry': The callback provided as parameter 2 is not a function.

2.3。尝试使用JS Interop

我什至尝试为JS的window.customElements.define创建一个互操作函数,但是错误是相同的。

@JS('window.customElements')
library web_components_interop;

import 'package:js/js.dart';

@JS('define')
external void registerWebComponent(String name,Object constructor,[Map<dynamic,dynamic> options]);

然后只需将上面的注册替换为registerWebComponent(GraphButton.tag,GraphButton);,现在将产生相同的错误消息。

3。其他有用的资源

是否有关于此主题的官方文档?我希望在AngularDart的文档中找到有关它的信息-因为在Angular中创建Web组件非常普遍-但到目前为止我还做不到。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)