如何使Web组件插槽正常工作?

时间:2018-07-24 09:41:50

标签: html web-component shadow-dom custom-element

我已经复制了MDN的示例(https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots),但无法正常工作 这是我的组件:

<link rel="import" href="../molecules/main-menu__topbar.html">


<template id="main-menu">
  <p>I'M THE MENU ELEMENT</span>
  <main-menu__topbar></main-menu__topbar>
  <main-menu__topbar>
    <span slot="my-text">Let's have some different text!</span>
  </main-menu__topbar>

</template>

<script>
  (function() {
    var importDoc = document.currentScript.ownerDocument;

    var proto = Object.create(HTMLElement.prototype);

    proto.createdCallback = function() {

      var template = importDoc.querySelector('#main-menu');

      var clone = document.importNode(template.content, true);

      var root = this.createShadowRoot();
      root.appendChild(clone);
    };

    document.registerElement('main-menu', {prototype: proto});
  })();
</script>

和导入的顶部栏:

<template id="main-menu__topbar">
  <div class="main-menu__topbar">
    <p>I'm the topbar</p>
    <p><slot name="my-text">My default text</slot></p>
  </div>
</template>

<script>
  (function() {
    var importDoc = document.currentScript.ownerDocument;

    var proto = Object.create(HTMLElement.prototype);

    proto.createdCallback = function() {

      var template = importDoc.querySelector('#main-menu__topbar');

      var clone = document.importNode(template.content, true);

      var root = this.createShadowRoot();
      root.appendChild(clone);
    };

    document.registerElement('main-menu__topbar', {prototype: proto});
  })();
</script>

如何使菜单中的第二个顶部栏显示“让我们有一些不同的文字!”?

1 个答案:

答案 0 :(得分:3)

<?php // You have this variable to compare against the database $email = $_POST[usu_email]; // You say it is working. // ... // Then, you certainly have a result... Say it's $found (true/false). // Build an array of all the response param you want to send as a response. if($found){ $result[email_exist] = "yes"; $result[message] = "The submitted email already exist."; }else{ $result[email_exist] = "no"; $result[message] = "A success message about the email here."; } // Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side. header("Content-type:application/json"); // Encode the array as a json and print it. That's what is sent in data as an Ajax response. echo json_encode($result); ?> 与Shadow DOM v0有关,它不适用于createShadowRoot()元素,而仅适用于<slot>元素。

<content>与Shadow DOM v1有关,它不适用于<slot>,而仅适用于createShadowRoot()

因为不建议使用Shadow DOM v0,所以我建议使用v1,因此应替换attachShadow()

createShadowRoot

注意:您还应该使用自定义元素v1而不是v0