VueJS中拆分API返回JSON为两个对象数组并渲染的实现
VueJS 拆分API返回数据为两个数组的实现方案
实现思路
- 借助Vue的计算属性处理API返回的原始数据
- 通过字段前缀(
r/s)区分数据归属,提取对应字段并重组为标准对象 - 将重组后的对象封装为数组,完全适配原有
v-for循环渲染逻辑
代码示例
1. 基础实现(API返回单个对象)
<template> <div> <!-- 原rItems渲染区域 --> <div class="r-block"> <div v-for="item in rItems" :key="item.id"> ID: {{ item.id }}<br> FI: {{ item.fi }}<br> TN: {{ item.tn }}<br> AN: {{ item.an }} </div> </div> <!-- 原sItems渲染区域 --> <div class="s-block"> <div v-for="item in sItems" :key="item.id"> ID: {{ item.id }}<br> FI: {{ item.fi }}<br> TN: {{ item.tn }}<br> AN: {{ item.an }} </div> </div> </div> </template> <script> export default { data() { return { apiRawData: null // 存储API返回的原始数据 } }, mounted() { // 模拟API请求,实际替换为你的接口调用逻辑 this.getApiData() }, methods: { async getApiData() { // 示例API返回数据 const res = { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID": "2", "sFI": "004", "sTN": "1002", "sAN": "03402" } this.apiRawData = res // 实际项目中可使用axios等工具: // const { data } = await axios.get('/your-api-endpoint') // this.apiRawData = data } }, computed: { rItems() { if (!this.apiRawData) return [] const rObj = {} // 筛选r前缀字段并重组 Object.keys(this.apiRawData).forEach(key => { if (key.startsWith('r')) { const newKey = key.slice(1).toLowerCase() rObj[newKey] = this.apiRawData[key] } }) return [rObj] // 封装为数组适配v-for }, sItems() { if (!this.apiRawData) return [] const sObj = {} // 筛选s前缀字段并重组 Object.keys(this.apiRawData).forEach(key => { if (key.startsWith('s')) { const newKey = key.slice(1).toLowerCase() sObj[newKey] = this.apiRawData[key] } }) return [sObj] // 封装为数组适配v-for } } } </script>
2. 适配API返回数组的情况
如果API返回的是多个该结构的对象数组,只需修改计算属性逻辑:
computed: { rItems() { if (!this.apiRawData || !Array.isArray(this.apiRawData)) return [] return this.apiRawData.map(item => { const rObj = {} Object.keys(item).forEach(key => { if (key.startsWith('r')) { const newKey = key.slice(1).toLowerCase() rObj[newKey] = item[key] } }) return rObj }) }, sItems() { if (!this.apiRawData || !Array.isArray(this.apiRawData)) return [] return this.apiRawData.map(item => { const sObj = {} Object.keys(item).forEach(key => { if (key.startsWith('s')) { const newKey = key.slice(1).toLowerCase() sObj[newKey] = item[key] } }) return sObj }) } }
关键说明
- 计算属性会自动响应
apiRawData的变化,无需手动触发数组更新 - 字段转换时统一将前缀后的键名转为小写,保证对象结构更规范
- 始终返回数组格式,完全兼容原有模板的
v-for循环,无需修改渲染逻辑
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

