我正在尝试生成具有可编辑字段和双向数据绑定的动态b表。
我希望没有任何硬编码的值。现在,我有:
<b-table striped hover :items="filtered">
<template v-slot:cell(issueDescription)="row">
<b-form-input v-model="row.item.issueDescription" />
</template>
<template v-slot:cell(endTime)="row">
<b-form-input v-model="row.item.endTime" />
</template>
<template v-slot:cell(startTime)="row">
<b-form-input v-model="row.item.startTime" />
</template>
</b-table>
位置:
filtered = [ { "issueDescription": "this is a description", "endTime": "2020-02-11T14:00:00.000Z",
"startTime": "2020-02-11T01:24:00.000Z" }]
如果我生成带有v-for的模板,那么我在每一列中都有可编辑的字段,但是在每个字段上都没有绑定。
<b-table striped hover :items="filtered">
<template v-for="x in filtered" v-slot:cell()="row">
<b-form-input v-model="row.item.BIND_TO_SPECIFIC_TABLE_ROW_COL" />
</template>
</b-table>
如何绑定到特定行,col?
我做了一个小提琴:https://jsfiddle.net/gfhu1owt/
如果要使所有字段都可编辑,则可以使用此语法。
<template v-slot:cell()="{ item, field: { key } }">
<b-form-input v-model="item[key]" />
</template>
与您所拥有的非常相似。您只需要使用插槽上下文对象中的key
。 (我已经简化了一点,但是和row.field.key
一样)。另请注意,我不在模板中使用v-for
,这是因为v-slot:cell()
是一个后备广告版位,除非定义了特定广告位,否则它对所有广告位均有效。例如,v-slot:cell(issueDescription)
将覆盖v-slot:cell()
字段的issueDescription
。
虽然上述方法可行,但是有一天您有一个自己不想编辑的字段,例如对象中的id
字段,可能会出现问题。
为了解决此问题,我已经定义了字段并将它们传递给表。我还向想编辑的字段添加了editable
属性。 (请注意,这不是字段对象中的标准内容,而是针对您的用例的特定内容)。
然后我创建了一个计算属性editableFields
,该属性将返回所有具有editable: true
的字段,然后在editableFields
内的v-for
中使用b-table
。
通过这种方式,您可以选择要在对象中编辑的属性。
new Vue({
el: "#app",
computed: {
editableFields() {
return this.fields.filter(field => field.editable)
}
},
data: {
filtered: [
{
"id": "1",
"issueDescription": "this is a description",
"endTime": "2020-02-11T14:00:00.000Z",
"startTime": "2020-02-11T01:24:00.000Z"
},
{
"id": "2",
"issueDescription": "this is a description",
"endTime": "2020-02-11T14:00:00.000Z",
"startTime": "2020-02-11T01:24:00.000Z"
}
],
fields: [
{ key: 'id', label: 'ID' },
{ key: 'issueDescription', label: 'Issue Description', editable: true },
{ key: 'startTime', label: 'Start Time', editable: true },
{ key: 'endTime', label: 'End Time', editable: true }
]
}
})
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.min.js"></script>
<div id='app'>
<b-table :items="filtered" :fields="fields">
<template v-for="field in editableFields" v-slot:[`cell(${field.key})`]="{ item }">
<b-input v-model="item[field.key]"/>
</template>
</b-table>
</div>