Aurelia select 初始值
Aurelia select initial value
我有以下代码:
javascript:
export class App {
values = [
{id: 0, text:'Text 1'},
{id: 1, text:'Text 2'},
{id: 2, text:'Text 3'}
];
obj = {
selected: 2
};
}
html:
<template>
<select value.bind="obj.selected">
<option repeat.for="option of values" value="${option.id}">${option.text}</option>
</select>
</template>
问题是 select
的初始值不是预期的第三个选项。
我需要做什么才能使其正常工作?
id
属性 是数字类型,因此您需要确保每个选项元素的 "value" 也是数字类型。这意味着您不想使用字符串插值绑定(例如 ${...}
),因为它们总是将源值转换为字符串。您也不想使用选项元素的 value
属性来存储值,因为该属性只接受字符串。而是使用 model
属性 这是一个特殊的 属性 aurelia 的绑定系统理解并可以存储任何类型。文档 here.
中讨论了这些场景
tldr:将您的选项元素绑定更改为:
<option repeat.for="option of values" model.bind="option.id">${option.text}</option>
我有以下代码:
javascript:
export class App {
values = [
{id: 0, text:'Text 1'},
{id: 1, text:'Text 2'},
{id: 2, text:'Text 3'}
];
obj = {
selected: 2
};
}
html:
<template>
<select value.bind="obj.selected">
<option repeat.for="option of values" value="${option.id}">${option.text}</option>
</select>
</template>
问题是 select
的初始值不是预期的第三个选项。
我需要做什么才能使其正常工作?
id
属性 是数字类型,因此您需要确保每个选项元素的 "value" 也是数字类型。这意味着您不想使用字符串插值绑定(例如 ${...}
),因为它们总是将源值转换为字符串。您也不想使用选项元素的 value
属性来存储值,因为该属性只接受字符串。而是使用 model
属性 这是一个特殊的 属性 aurelia 的绑定系统理解并可以存储任何类型。文档 here.
tldr:将您的选项元素绑定更改为:
<option repeat.for="option of values" model.bind="option.id">${option.text}</option>