我正在尝试提出一个Blazor实现,它使用带有多个复选框的数组类型模型。
Vue组件:
<template>
<div>
<b-form-group label="Using sub-components:">
<b-form-checkbox-group id="checkbox-group-2" v-model="selected" name="flavour-2">
<b-form-checkbox value="orange">Orange</b-form-checkbox>
<b-form-checkbox value="apple">Apple</b-form-checkbox>
<b-form-checkbox value="pineapple">Pineapple</b-form-checkbox>
<b-form-checkbox value="grape">Grape</b-form-checkbox>
</b-form-checkbox-group>
</b-form-group>
<div>Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [], // Must be an array reference!
}
}
}
</script>
Blazor组件:
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="@id" name="@name" @onchange="@((ChangeEventArgs) => CheckedChanged(ChangeEventArgs, value))">
<label class="custom-control-label" for="@id">@label</label>
</div>
@code {
[Parameter]
public string id { get; set; }
[Parameter]
public string name { get; set; }
[Parameter]
public object value { get; set; }
[Parameter]
public List<object> model { get; set; }
[Parameter]
public EventCallback<List<object>> modelChanged { get; set; }
[Parameter]
public string label { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
}
protected void CheckedChanged(ChangeEventArgs args, object value)
{
if(!model.Any(i => i == value))
{
model.Add(value);
}
else
{
model.Remove(value);
}
}
}
用法:
@foreach (string timezone in DistinctTimezones)
{
<BCheckbox @bind-model="@FilterTimezones" value="@timezone" label="@timezone" id="@(string.Format("timezone_{0}", timezone))" name="@(string.Format("timezone_{0}", timezone))" />
}
<p>Selected:</p>
@foreach(var timezone in FilterTimezones)
{
@timezone
}
@code {
protected List<string> DistinctTimezones { get; set; } = new List<string>{"Central", "Eastern"};
protected List<object> FilterTimezones { get; set; } = new List<object>();
}
当我选中这些复选框时,FilterTimezone
对象不会使用选中的复选框中的值进行更新。这是不是已经有可能了,我把它复杂化了?我只知道将值绑定到非集合类型。
发布于 2020-04-24 16:24:02
我会这样做(字符串在这里只是为了简化,以获得想法) CollectionCheckBox.razor
<input type="checkbox" @bind=isChecked />
@code
{
[Parameter]
public string Value { get; set; }
[Parameter]
public List<string> Model {get; set;}
private bool isChecked
{
get => Model.Any(el => el == Value);
set
{
if(value)
{
if(!Model.Any(el => el == Value) Model.Add(Value);
}
else
Model.Remove(Value);
}
}
}
然后,在父组件中,您只需执行
<CollectionCheckBox Model="@Model", Value="Orange" />
<CollectionCheckBox Model="@Model", Value="Apple" />
<CollectionCheckBox Model="@Model", Value="Pineapple" />
<CollectionCheckBox Model="@Model", Value="Grape" />
@code
{
private List<string> Model = new List<string();
}
https://stackoverflow.com/questions/61397293
复制相似问题