Web Component

专门用来渲染 web component 的组件,可以通过这种方式来扩展 amis 组件,比如使用 Angular。

基本用法

比如下面这个 web component

  1. <random-number prefix="hello" class="my-class"></random-number>

对应代码类似

  1. import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter';
  2. class RandomNumber extends HTMLElement {
  3. connectedCallback() {
  4. const prefix = this.getAttribute('prefix') || '';
  5. const shadow = this.attachShadow({mode: 'open'});
  6. const text = document.createElement('span');
  7. text.textContent = `${prefix}: ${Math.floor(Math.random() * 1000)}`;
  8. shadow.appendChild(text);
  9. setInterval(function () {
  10. const count = `${prefix}: ${Math.floor(Math.random() * 1000)}`;
  11. text.textContent = count;
  12. }, 2000);
  13. }
  14. }
  15. customElements.define('random-number', RandomNumber);

使用 amis 可以这样渲染出来

  1. {
  2. "type": "web-component",
  3. "tag": "random-number",
  4. "props": {
  5. "prefix": "hello",
  6. "class": "my-class"
  7. }
  8. }

其中 tag 指定标签,属性放在 props 对象里,props 里的值支持变量替换,比如:

  1. {
  2. "data": {
  3. "text": "World"
  4. },
  5. "type": "page",
  6. "body": {
  7. "type": "web-component",
  8. "tag": "random-number",
  9. "props": {
  10. "prefix": "${text}"
  11. }
  12. }
  13. }

属性表

属性名 类型 默认值 说明
type string "web-component" 指定为 web-component 渲染器
tag string 具体使用的 web-component 标签
props object 标签上的属性
body SchemaNode 子节点