使用 Aurelia,如何为自定义属性设置默认值

Using Aurelia, how to set a default value for a custom attribute

查看

<template>
  <div single-value-attrib="${color}"></div>
  <div single-value-attrib.bind="color"></div>
  <input type="text" value.bind="color" />
</template>

查看模型

export class SingleValueAttribCustomAttribute {
  static inject = [Element];
  color = 'orange';
  constructor(element) {

    this.element = element;
    this.element.style.width = this.element.style.height = '100px';
  }

  bind() {
    this.element.style.backgroundColor = this.value;
  }

  valueChanged(newValue, oldValue) {
    this.element.style.backgroundColor = newValue;
  }
}

我原以为 viewModel 中的 color='orange'; 会映射到视图上的颜色,从而将默认颜色设置为橙色。更改输入框中的颜色按预期工作。我知道您可以将 this.value 设置为默认颜色,但我只是认为绑定的工作方式与骨架导航中的工作方式相同,其中输入框具有 firstName 和 lastName[=14= 的默认值]

首先,请注意 this.color 没有在代码视图模型中的任何地方使用,因此设置它实际上不会在代码中执行任何操作,因为它存在。

经过一番尝试,我确定在这种特定情况下,您最好的选择是在构造函数中设置背景颜色并删除 bind 函数。我在这里创建了一个 gist.run:https://gist.run/?id=a15e0305f082f6ef080364caff2a1ec1

这是自定义属性的虚拟机:

export class SingleValueAttribCustomAttribute {
  static inject = [Element];
  defaultColor = 'orange';
  constructor(element) {

    this.element = element;
    this.element.style.width = this.element.style.height = '100px';
    this.element.style.backgroundColor = this.defaultColor; 
  }

  valueChanged(color) {
    if(color.trim() !== '') {
      this.element.style.backgroundColor = color;
    }
  }
}

您可能希望在 valueChanged 中删除 color 上的空字符串检查,具体取决于您的用例。