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

时间:2017-03-19 11:49:36

标签: aurelia custom-element selectors-api

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

<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,但我不知道如何仅在字段集组件中选择元素(而不是可以包含其他字段集的整个页面)。

1 个答案:

答案 0 :(得分:0)

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

GistRun:https://gist.run/?id=aa1e8239736e0de11f73116966af9ac9

<强> fieldset.html

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

<强> fieldset.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`);
    }
  }
}

<强> consumer.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');
        ……
    }