如何通过配置数组在Vuetify表格中读取已解析JSON的嵌套数据
解决方案
这个需求完全可以实现,核心问题是你当前直接用service[serviceProperty.value]的写法只能读取对象的顶层属性,无法解析带点、数组下标的嵌套路径字符串,你只需要补充一个根据路径字符串提取对象嵌套属性的工具方法即可。
具体实现步骤
1. 新增嵌套属性读取方法
在组件的methods中加入以下通用方法,支持解析带点、数组下标的路径:
methods: { getNestedValue(obj, path) { // 把路径里的方括号替换为点,比如locations[1]转为locations.1 const processedPath = path.replace(/\[(\w+)\]/g, '.$1'); // 按点分割成路径数组 const pathSegments = processedPath.split('.'); // 逐层遍历取值 return pathSegments.reduce((current, segment) => { // 遇到空值直接返回空避免报错 return current && current[segment] !== undefined ? current[segment] : ''; }, obj); } }
2. 修改表格模板的取值逻辑
把原来<td>里的取值代码替换为调用上面的方法:
<td>{{ getNestedValue(service, serviceProperty.value) }}</td>
完整修改后的代码
HTML部分
<v-simple-table fixed-header height="300px"> <template v-slot:default> <thead> <tr> <th class="text-left"> Attribute </th> <th class="text-left"> Value </th> </tr> </thead> <tbody> <tr v-for="(serviceProperty, idx) in serviceProperties" :key="idx"> <th>{{ serviceProperty.label }}</th> <td>{{ getNestedValue(service, serviceProperty.value) }}</td> </tr> </tbody> </template> </v-simple-table>
JS部分
export default { name: "Details", data() { return { loading: true, service: {}, serviceProperties: [ { label: 'Description', value: 'description' }, { label: 'Location', value: 'organization.locations[1].streetAddress' }, { label: 'EIN', value: 'organization.EIN' } ] }; }, props: ["serviceId"], async created() { this.service = await Vue.$serviceService.findOne(this.serviceId); this.loading = false; }, methods: { getNestedValue(obj, path) { const processedPath = path.replace(/\[(\w+)\]/g, '.$1'); const pathSegments = processedPath.split('.'); return pathSegments.reduce((current, segment) => { return current && current[segment] !== undefined ? current[segment] : ''; }, obj); } } };
额外说明
- 如果你的项目已经引入了Lodash,可以直接使用
_.get(service, serviceProperty.value, '')方法,不需要自己写工具函数,效果完全一致 - 方法里做了空值兼容,即使某层嵌套属性不存在也不会抛出报错,会返回空字符串展示
内容的提问来源于stack exchange,提问作者M. Straw
相关产品推荐
相关产品推荐

