是否可以在自定义元素中声明<template>?怎么样?

时间:2019-09-27 14:58:29

标签: javascript html

我正在尝试在js自定义元素中声明<template>。模板内部是<style><slot>标签。当我在页面中使用内容时,内容不会被替换。

我的代码如下:

(function(){
    class SampleElement extends HTMLElement {
        constructor() {
            super();

            this.attachShadow({ mode: 'open' });

            const template = document.createElement('template');
            template.innerHTML = `
                <slot name="sample">text</slot>
            `;
            document.body.appendChild(template);
        }
    }

    customElements.define('sample-element', SampleElement);
})();

并在我的HTML中:

<sample-element>
    <div slot="sample">new text</div>
</sample-element>

如何替换自定义元素内模板中的广告位值?

1 个答案:

答案 0 :(得分:0)

根据您所写的内容,我假设您想使用模板的innerHTML作为自定义元素的模板。

(function () {
 
  const template = document.createElement('template');
  
  template.innerHTML = `
    <style>
      :host {
        display:block;
      }
    </style>

   <div>
    <slot name="replace">I am the fallback</slot>
   </div>
  `;
  
  
  class El extends HTMLElement {
    constructor() {
      super();
      // attach the shadow root to our element
      this.attachShadow({ mode: 'open' });
      // using the template innerHTML as the custom element scaffold/template
      this.shadowRoot.appendChild(template.content.cloneNode(true))
    }
  }
  
  
  customElements.define('my-el', El);
})();
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

</head>
<body>
 <my-el></my-el>
 <my-el>
   <span slot="replace">I am the override</span>
 </my-el>
  
</body>
</html>