如何从自定义渲染的Bootstrap-Vue表格获取数据项数组
解决BootstrapVue表格渲染后数据提取问题
嘿,我懂你想要把BootstrapVue表格里自定义渲染后的内容转换成指定格式的outputItems数组的需求。其实不用去操作DOM提取内容,咱们可以直接基于原items数组和fields配置,把表格里的渲染逻辑抽出来复用,生成目标数据,这样既高效又可靠。
实现思路
核心就是遍历每个原始数据项,根据fields数组里的配置(键名、标签、渲染规则),逐一对应生成outputItems里的每个对象:
- 虚拟列
index:直接取数组索引+1 - 自定义格式化列
name:把last转大写后和first拼接成LAST,First格式 - 虚拟复合列
nameage:拼接first name和age的字符串 - 常规列(age、sex):直接映射值,注意键名要用
fields里的label(比如Age、Sex)
完整代码实现
<template> <div> <b-table small :fields="fields" :items="items" responsive="sm"> <!-- A virtual column --> <template v-slot:cell(index)="data"> {{ data.index + 1 }} </template> <!-- A custom formatted column --> <template v-slot:cell(name)="data"> <b class="text-info">{{ data.value.last.toUpperCase() }}</b>, <b>{{ data.value.first }}</b> </template> <!-- A virtual composite column --> <template v-slot:cell(nameage)="data"> {{ data.item.name.first }} is {{ data.item.age }} years old </template> <!-- Optional default data cell scoped slot --> <template v-slot:cell()="data"> <b-form-input v-model="data.value" placeholder="Enter custom value" /> </template> </b-table> <!-- 可以在这里预览生成的outputItems --> <pre>{{ outputItems }}</pre> </div> </template> <script> export default { data() { return { fields: [ // A virtual column that doesn't exist in items 'index', // A column that needs custom formatting { key: 'name', label: 'Full Name' }, // A regular column 'age', // A regular column 'sex', // A virtual column made up from two fields { key: 'nameage', label: 'First name and age' } ], items: [ { name: { first: 'John', last: 'Doe' }, sex: 'Male', age: 42 }, { name: { first: 'Jane', last: 'Doe' }, sex: 'Female', age: 36 }, { name: { first: 'Rubin', last: 'Kincade' }, sex: 'Male', age: 73 }, { name: { first: 'Shirley', last: 'Partridge' }, sex: 'Female', age: 62 } ] } }, computed: { outputItems() { return this.items.map((item, index) => { const result = {} // 遍历每个字段配置,生成对应的键值对 this.fields.forEach(field => { // 处理字段配置的两种形式:字符串或对象 const fieldKey = typeof field === 'string' ? field : field.key const fieldLabel = typeof field === 'string' ? fieldKey.charAt(0).toUpperCase() + fieldKey.slice(1) : field.label switch (fieldKey) { case 'index': result[fieldLabel] = index + 1 break case 'name': result[fieldLabel] = `${item.name.last.toUpperCase()},${item.name.first}` break case 'nameage': result[fieldLabel] = `${item.name.first} is ${item.age} years old` break default: // 处理常规字段,比如age、sex,空值时返回空字符串 result[fieldLabel] = item[fieldKey] || '' } }) return result }) } } } </script>
说明
- 计算属性
outputItems:利用Vue的计算属性,当items或fields变化时会自动重新计算,保证数据同步。 - 字段配置兼容:同时兼容了
fields里的字符串形式(比如'index'、'age')和对象形式(比如{ key: 'name', label: 'Full Name' }),自动提取key和label。 - 自定义逻辑映射:把表格插槽里的渲染逻辑(比如名字大写拼接、索引计算)搬到了计算属性里,确保生成的
outputItems和表格显示内容完全一致。
运行代码后,outputItems就会完全符合你期望的格式啦~
内容的提问来源于stack exchange,提问作者Kingz
相关产品推荐
相关产品推荐

