【问题标题】:Aurelia custom attribute on containerless custom element, does not get element无容器自定义元素上的 Aurelia 自定义属性,未获取元素
【发布时间】:2019-05-24 13:54:27
【问题描述】:

我正在 aurelia 中开发一个名为 OnScreenKeyboardCustomAttribute 的自定义属性。工作完成后,我试图使用一个包含输入的自定义元素,我希望这个元素在该输入上工作。默认情况下,我在属性类中获取元素并期望它是输入或文本字段。

但是,在该自定义属性上,输入元素位于其他一些元素中。所以我认为下一步是进入元素并实现内部输入。这是可能的,但是当自定义属性具有无容器注释时,我在属性类中没有收到任何元素,而是收到<!--anchor-->。那么如何才能实现到内部元素呢?

自定义元素 - 视图模型

import {
  containerless,
} from 'aurelia-framework';

@containerless()
export class CInputCustomAttribute {
}

自定义元素 - 视图

<template>
  <div class.bind="paClass ? paClass : 'row margin_bottom'">
    <div class.bind="labelClass ? labelClass : 'column_large_3 column_small_4'">
      <label for="${id}" class="label_inline" class.bind="errors.length ? 'text_red' : '' "><span class="required_star"
          if.bind="star">*</span>${label}</label>
    </div>

    <div class.bind="inputClass ? inputClass : 'column_large_9 column_small_8'">
      <input id="${id}" placeholder="${placeholder}" class="input toggle_input" class.bind="errors.length ? 'validate-error' : '' "
        value.bind="value" type="${type}" maxlength="${max ? max : 5000}" click.trigger="typeof runFunction=='function' ? runFunction():''">
      <span class="message_red">
        <template repeat.for="error of errors">
          ${error.error.message}<br>
        </template>
      </span>
    </div>
    <slot></slot>
  </div>
</template>

自定义属性 - 视图模型

@inject(Element, BindingEngine)
export class PaOnScreenKeyboardCustomAttribute {

constructor(element, bindingEngine) {
    this.element = element;
    console.log(this.element);
  }

用法

<c-input type="text" id="username" pa-on-screen-keyboard max="11">

console: <!--anchor-->

【问题讨论】:

  • 再次提醒,这里将删除签名。此外,religious material 将被删除。我们这里有一个奇怪的有神论者,他们决心传教,但通常不受欢迎。请将其保存在您的博客、社交媒体或专门讨论有神论的网站上。

标签: element aurelia custom-attributes custom-element


【解决方案1】:

如果您使用containerless,则没有元素可以传递给您的自定义属性。这就是使用containerless 的本质。自定义元素在运行时从标记中移除,但您的自定义属性必须附加在某处,因此框架将其放在“锚”注释元素上。因此,这就是它传递给您的属性的内容。

我的建议,这是我始终的建议,除非绝对必要,否则不要使用containerless。不要使用containerless b/c 它“让你的标记在运行时看起来更好”或者因为“那里的自定义元素破坏了我们的 CSS”。自从 Aurelia 公开发布之前,我就一直在构建它,除了包装我无法修改 CSS 的第三方组件之外,我还没有需要使用 containerless。我什至有一条规则在我的 TSLint 规则中不使用它。

而这种情况正是我避免使用containerless 的确切原因。它会导致不稳定的问题。自定义元素通常应该就是那个......元素。无容器元素并不是真正的元素。

【讨论】:

  • "...而且无容器元素并不是真正的元素。"。很好的答案@Ashley Grant。谢谢。
  • 我遇到了同样的问题,因为我想在元素上使用 querySelector()。即使我理解并分享你的观点,我认为在某个地方,也许是 Element,应该有人处理这种情况,回馈开发人员可以使用的一些钩子。现在和对我来说,这有点像一个错误。顺便说一句,感谢阿什利的解释
  • 这不是错误,这是预期的行为。通过使用containerless,您可以告诉框架不要在运行时将自定义元素本身放入您的标记中。然后您尝试在不存在的元素上调用querySelector。你必须选择一个或另一个。要么使用containerless 将元素保留在标记之外,要么不使用它并且能够在元素上使用querySelector。您不能在不存在的对象上调用函数。
猜你喜欢
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多