如何在Aurelia自定义元素中引用特定元素<slot>?



我想在Aurelia中创建自定义字段集,我需要在"slot"标签中设置标签元素的样式(宽度((请参阅下面的示例用法(。如何访问这些元素?到目前为止,我所拥有的是

<template>
  <require from="./ib-fieldset.css"></require>
  <fieldset style.bind="style">
    <legend>${title}</legend>
    <slot></slot>
  </fieldset>
</template>

import {bindable} from 'aurelia-framework';
import * as $ from 'jquery';
export class IbFieldset {
  @bindable title: string;
  @bindable top: number;
  @bindable left: number;
  @bindable labelWidth: number;
  style: string;
  attached() {
    this.title = ` ${this.title} `;
    this.style = `position: absolute; top: ${this.top}px; left: ${this.left}px;`;
  }
}

我是这样使用它的:

  <ib-fieldset title="Address" top="100" left="200" labelWidth="100">
    <label for="firstName">First name:</label>
    <input id="firstName" type="text">
    <label for="lastName">Last name:</label>
    <input id="lastName" type="text">
  </ib-fieldset><br>

我尝试使用 jquery,但我不知道如何仅选择字段集组件中的元素(而不是可以包含其他字段集的整个页面(。

像Aurelia的大多数情况一样,不需要jQuery。

要点运行:https://gist.run/?id=aa1e8239736e0de11f73116966af9ac9

字段集.html

<template>
  <fieldset style="position: absolute; top: ${top}px; left: ${left}px;">
    <legend>${title}</legend>
    <slot ref="slotElement"></slot>
  </fieldset>
</template>

字段集.js

import {bindable} from 'aurelia-framework';
export class IbFieldset {
  @bindable title: string;
  @bindable top: number;
  @bindable left: number;
  @bindable labelWidth: number;
  attached() {
    this.title = ` ${this.title} `;
    let labels = this.slotElement.querySelectorAll('label');
    for (let label of Array.from(labels)) {
        label.setAttribute('width', `${labelWidth}px`);
    }
  }
}

消费者.html

<require from="./fieldset"></require>
<ib-fieldset title="Address" top="100" left="200" label-width="100">
  <label for="firstName">First name:</label>
  <input id="firstName" type="text"/>
  <label for="lastName">Last name:</label>
  <input id="lastName" type="text"/>
</ib-fieldset><br>

要注入元素:

import {inject} from ‘aurelia-framework’;
@inject(Element)
export class IbFieldset {
    constructor(element) {
        this.element = element;
    }
    attached() {
        let labels = this.element.querySelectorAll('label');
        ……
    }

相关内容

最新更新