Nuxt应用中使用asyncData请求如何仅保留JSON所需字段
实现方案说明
核心逻辑是在asyncData请求拿到全量Knack响应后,先做字段裁剪生成仅包含所需字段的精简数组,再返回给页面上下文。全量原始数据仅会在asyncData的局部作用域内存在,执行完成后会被GC回收,不会挂载到Vue实例上,前端侧和控制台都只会暴露你需要的字段。
代码示例
首先先定义你需要保留的字段映射表,key为你后续模板中使用的自定义字段名,value为Knack接口返回的原始字段名(Knack的字段一般为field_xxx格式,可根据你实际返回的字段名调整):
const REQUIRED_FIELDS = { id: 'id', title: 'field_123', createTime: 'field_124', author: 'field_125', coverImg: 'field_126', viewCount: 'field_127', category: 'field_128', summary: 'field_129', status: 'field_130', updateTime: 'field_131' }
Nuxt2 实现代码
// pages/xxx.vue import axios from 'axios' export default { async asyncData() { const REQUIRED_FIELDS = { // 替换为你实际需要的字段映射 id: 'id', title: 'field_123', createTime: 'field_124', author: 'field_125', coverImg: 'field_126', viewCount: 'field_127', category: 'field_128', summary: 'field_129', status: 'field_130', updateTime: 'field_131' } try { // 请求Knack接口获取全量数据 const res = await axios.get('你的Knack接口请求地址', { headers: { 'X-Knack-Application-Id': '你的Knack应用ID', 'X-Knack-REST-API-Key': '你的Knack API密钥' } }) const rawRecords = res.data.records || [] // 裁剪字段生成精简数组 const filteredRecords = rawRecords.map(rawItem => { const filteredItem = {} Object.entries(REQUIRED_FIELDS).forEach(([customKey, rawKey]) => { // 若Knack返回的字段是嵌套结构,可自行调整取值逻辑,例:rawItem[rawKey]?.raw filteredItem[customKey] = rawItem[rawKey] }) return filteredItem }) // 仅返回裁剪后的精简数据,全量数据不会被挂载到页面实例 return { records: filteredRecords } } catch (err) { console.error('接口请求失败', err) return { records: [] } } } }
Nuxt3 适配代码
// pages/xxx.vue const REQUIRED_FIELDS = { // 替换为你实际需要的字段映射 id: 'id', title: 'field_123', createTime: 'field_124', author: 'field_125', coverImg: 'field_126', viewCount: 'field_127', category: 'field_128', summary: 'field_129', status: 'field_130', updateTime: 'field_131' } const { data: records } = await useAsyncData('knack-records', async () => { const rawRes = await $fetch('你的Knack接口请求地址', { headers: { 'X-Knack-Application-Id': '你的Knack应用ID', 'X-Knack-REST-API-Key': '你的Knack API密钥' } }) const rawRecords = rawRes.records || [] return rawRecords.map(rawItem => { const filteredItem = {} Object.entries(REQUIRED_FIELDS).forEach(([customKey, rawKey]) => { filteredItem[customKey] = rawItem[rawKey]?.raw || rawItem[rawKey] }) return filteredItem }) })
提示:如果需要进一步降低内存占用,裁剪逻辑完成后可手动将
rawRecords、res等原始数据变量赋值为null,加快GC回收速度。
内容的提问来源于stack exchange,提问作者michaelstory
相关产品推荐
相关产品推荐

