gpt4 book ai didi

aurelia - Aurelia 自定义元素中的 2 路数据绑定(bind) - 将自定义元素绑定(bind)到父 View 模型

转载 作者:行者123 更新时间:2023-12-04 02:41:46 25 4
gpt4 key购买 nike

在我的应用程序中,我做了很多“服务”,我可以将它们注入(inject)到我的 View 模型中,以节省一些冗余和时间。

现在我希望更进一步,制作这些表单元素(选择、文本、复选框 - 初学者的选择下拉菜单)并将它们转换为自定义元素,仅在自定义元素中注入(inject)服务。

我可以让它在某种程度上发挥作用。当我在“父” View 中需要它时显示自定义元素(在本例中为选择),但是当我更改自定义选择元素的选定值时,它不会绑定(bind)到“父” View 模型,这是我的要求.

我希望能够通过其模板中的 bind 属性将我选择的值从自定义元素绑定(bind)到“父” View 模型上的属性。

我将在几分钟内更新其中的一小段代码。

create.js(我称之为父 View 模型)

import {bindable} from 'aurelia-framework';
export class Create{
heading = 'Create';
@bindable myCustomElementValue = 'initial value';
}

create.html(父 View )
<template>
<require from="shared/my-custom-element"></require>
<my-custom selectedValue.bind="myCustomElementValue"></my-custom>
<p>The output of ${myCustomElementValue} should ideally be shown and changed here, as the select dropdown changes</p>
</template>

我的自定义.js
import { inject, bindable} from 'aurelia-framework';
import MyService from 'my-service';

@inject(MyService )
export class MyCustomCustomElement {
@bindable selectedValue;

constructor(myService ) {
this.myService = myService ;
}

selectedValueChanged(value) {
alert(value);
this.selectedValue = value;
}

async attached() {
this.allSelectableValues = await this.myService.getAllValues();
}
}

最初发生的情况是 create.html View 输出“初始值”,当我更改自定义元素选择的值时,新选择的值会被警告出来,但它不会更新绑定(bind)的父变量,它仍然只是显示“初始值”。

最佳答案

这里有几个问题:

  • 由于不区分大小写,您需要对 DOM 中的任何属性名称进行 kebab-case
    selected-value.bind="property"
    不是
    selectedValue.bind="property"
  • 您需要双向绑定(bind)。创建 @bindable 时使用装饰器,参数之一是 BindingMode用于设置默认绑定(bind)模式。

    Aurelia 设置了一些合理的默认值,例如input value.bind=".." 的默认值是两种方式而不是明确的

    如果您不想设置默认绑定(bind)模式,则可以明确使用绑定(bind):
    selected-value.two-way="prop"

  • 希望这可以帮助 :)

    编辑:我认为这个答案后 API 发生了一些变化。
    @bindable装饰器具有以下标志:
    bindable({
    name:'myProperty',
    attribute:'my-property',
    changeHandler:'myPropertyChanged',
    defaultBindingMode: bindingMode.oneWay,
    defaultValue: undefined
    })

    检查快速引用的最佳位置之一是文档中的 Aurelia 备忘单:

    http://aurelia.io/docs/fundamentals/cheat-sheet

    关于aurelia - Aurelia 自定义元素中的 2 路数据绑定(bind) - 将自定义元素绑定(bind)到父 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297363/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com