使用 aurelia 自定义元素作为父元素时不显示按钮元素

button element's dont display when using aurelia custom element as parent

我正在尝试创建一个自定义容器元素来跟踪一些子按钮元素。问题是当我这样做时按钮不显示在网页上。我究竟做错了什么?我还尝试使用 aurelia @children 装饰器在我的容器视图模型中添加按钮,但这似乎也不起作用。请帮忙!

如果我将按钮元素移出主要自定义元素,它们就会出现。

我的自定义元素视图main.html

<template>   
    <div class="col-sm-9" style="text-align: left;">        
    </div>
</template>

自定义视图模型main.js

import {children} from 'aurelia-framework';
 export class main {
    @children('button') buttons;
    constructor() {
        console.log("in the main constructor");
    }
}

`

app.html

<template>
  <require from="./widgets/main"></require>
  <main>
      <button class="btn btn-default" type="button">On</button>
      <button class="btn btn-default" type="button">Off</button>
  </main>      
</template>

这个答案已经过时了!!!

请在此处查看 Aurelia 文档以获取当前答案:http://aurelia.io/hub.html#/doc/article/aurelia/templating/latest/templating-content-projection


您需要在自定义元素的视图文件中包含 <content></content> 元素。如果您只想显示自定义元素内容中的 button 个元素,请使用 <content select="button"></content>

请注意,这将在 Aurelia RC1 中更改为使用 Shadow DOM 规范已更改为的命名插槽标准(尽管目前没有浏览器支持它)。

这是一个 运行 示例: https://gist.run/?id=4314bba289d20cf491eb82d5c620f9c0 您会注意到我如何在示例中使用 select 属性和 css 样式选择器。我还使用了没有选择器的 content 元素来展示它是如何作为一个包罗万象的。

但是,是的,这很快就会改变。我们现在正在努力实施 slot

app.html

<template>
  <require from="./custom-element"></require>
  <my-custom-element>
      <button class="btn btn-default" type="button">On</button>
      <div>
        This div falls back to &lt;content&gt; since nothing more specific chooses it. <br />
        Notice how it is displayed last b/c of this.<br />
        Remove &lt;content /&gt; element in custom element and this won't be used in the rendering of the custom element.
      </div>
      <div class="footer">Footer</div>
      <button class="btn btn-default" type="button">Off</button>
  </my-custom-element>      
</template>

自定义-element.html

<template>   
    <content select="button"></content>
    <content select="div.footer"></content>
    <content></content>
</template>

自定义-element.js

import {customElement, children} from 'aurelia-framework';

@customElement('my-custom-element')
export class MyCustomElement {
  @children('button') buttons;
  constructor() {
  }

  bind() {
    console.log(this.buttons);
  }
}

哦,顺便说一句,如果您认为自己可能想要使用 Aurelia,则应避免创建名称中没有破折号的自定义元素(main 没有破折号)作为 Web 组件自定义元素的自定义元素。