Vue 3 中使用 Fetch API 处理复杂数据并动态填充下拉菜单的实践

Vue 3 中使用 Fetch API 处理复杂数据并动态填充下拉菜单的实践

本文探讨了在 vue 3 应用中,如何从 fetch api 获取包含复杂结构的数据,并将其有效转换为适合动态填充下拉菜单的独特选项。核心在于理解 api 响应结构,并利用 j*ascript 的 `map` 和 `set` 方法对数据进行高效转换和去重,以确保下拉菜单正确渲染所需数据。

引言:Vue 3 中数据获取与下拉菜单填充的挑战

在现代前端开发中,从后端 API 获取数据并将其动态渲染到用户界面是常见的需求。尤其是在构建表单时,下拉菜单(

例如,一个 API 可能返回一系列事件数据,每个事件对象包含 reason(原因)、condition(条件)和 incidentType(事件类型)等属性。如果我们的目标是分别创建三个下拉菜单,分别列出所有事件中出现过的唯一原因、唯一条件和唯一事件类型,那么直接使用原始数据是行不通的。

问题剖析:原始数据结构与预期不符

在上述场景中,常见的误区是假设 API 会直接返回预分类好的数组,例如 data.reasons、data.conditions 等。然而,实际的 API 响应通常是一个扁平的数组,其中每个元素都是一个完整的事件对象。

假设 API 返回的数据结构大致如下:

[
  {
    "id": "1",
    "reason": "Accident",
    "condition": "Wet",
    "incidentType": "Road Closure"
  },
  {
    "id": "2",
    "reason": "Construction",
    "condition": "Dry",
    "incidentType": "Lane Blockage"
  },
  {
    "id": "3",
    "reason": "Accident",
    "condition": "Wet",
    "incidentType": "Road Closure"
  },
  {
    "id": "4",
    "reason": "Maintenance",
    "condition": "Icy",
    "incidentType": "Shoulder Work"
  }
]

如果尝试在 Vue 组件中直接使用 this.dropdownData.reasons = [...data.reasons] 这样的代码,就会因为 data 对象(在这里 data 是上述数组本身)上不存在 reasons 属性而导致数据无法填充。这正是导致下拉菜单无法正常显示数据的原因:虽然数据成功获取,但其结构与组件期望的结构不匹配。

解决方案:利用 map 和 Set 进行数据转换与去重

为了将上述扁平的事件对象数组转换为适合下拉菜单的唯一选项列表,我们需要执行两个关键的数据操作:

  1. 提取特定属性值: 从每个事件对象中提取出我们感兴趣的属性(如 reason、condition、incidentType)。
  2. 确保值的唯一性: 从提取出的值列表中去除所有重复项。

J*aScript 的 Array.prototype.map() 和 Set 数据结构是实现这一目标的高效工具。

步骤一:提取特定属性值

map() 方法会遍历数组中的每个元素,并对每个元素执行一个回调函数,然后返回一个新的数组,新数组的元素是回调函数的结果。

Content at Scale Content at Scale

SEO长内容自动化创作平台

Content at Scale 154 查看详情 Content at Scale

例如,要提取所有事件的 reason 属性:

const reasonsArray = data.map(el => el.reason);
// 结果可能是:["Accident", "Construction", "Accident", "Maintenance"]

步骤二:确保值的唯一性

Set 是一种集合数据结构,它只存储唯一的值。将一个数组传递给 Set 的构造函数,可以快速创建一个包含所有唯一值的新集合。然后,可以使用展开运算符 (...) 将 Set 转换回一个数组。

const uniqueReasonsSet = new Set(reasonsArray);
// 结果是 Set {"Accident", "Construction", "Maintenance"}

const uniqueReasons = [...uniqueReasonsSet];
// 结果是 ["Accident", "Construction", "Maintenance"]

整合转换逻辑

将这两个步骤整合到 Vue 组件的数据处理逻辑中,可以得到以下修正后的代码:

// ...
.then((data) => {
  // data 现在是一个事件对象数组
  this.dropdownData = {
    reasons: [...new Set(data.map(el => el.reason))],
    conditions: [...new Set(data.map(el => el.condition))],
    incidentTypes: [...new Set(data.map(el => el.incidentType))]
  };
})
// ...

这段代码首先对 data 数组进行 map 操作,提取出各自的属性值数组,然后通过 new Set() 去除重复项,最后再用展开运算符将其转换回数组,并赋值给 dropdownData 对象的相应属性。这样,dropdownData.reasons、dropdownData.conditions 和 dropdownData.incidentTypes 就会包含下拉菜单所需的唯一选项列表。

完整 Vue 3 组件示例

下面是修正后的 Vue 3 组件代码,展示了如何正确地获取数据并填充下拉菜单:

<template>
  <div>
    <div>to wit: {{ dropdownData }}</div>
    <select v-model="reason">
      <option v-for="r in dropdownData.reasons" :value="r" :key="r">{{ r }}</option>
    </select>
    <select v-model="condition">
      <option v-for="c in dropdownData.conditions" :value="c" :key="c">{{ c }}</option>
    </select>
    <select v-model="incidentType">
      <option v-for="type in dropdownData.incidentTypes" :value="type" :key="type">{{ type }}</option>
    </select>
    <button @click="getData">Get Data</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      reason: null,
      condition: null,
      incidentType: null,
      dropdownData: {
        reasons: [],
        conditions: [],
        incidentTypes: []
      }
    }
  },
  mounted() {
    this.fetchDropdownData()
  },
  methods: {
    fetchDropdownData() {
      // 实际 API 地址,这里使用一个环境变量来模拟
      // 例如:https://eapps.ncdot.gov/services/traffic-prod/v1/incidents?verbose=true
      fetch(`${import.meta.env.VITE_API_VERBOSE}`)
        .then((response) => {
          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.json()
        })
        .then((data) => {
          // 核心修正:使用 map 提取数据,并使用 Set 去重
          this.dropdownData = {
            reasons: [...new Set(data.map(el => el.reason))],
            conditions: [...new Set(data.map(el => el.condition))],
            incidentTypes: [...new Set(data.map(el => el.incidentType))]
          }
        })
        .catch((error) => {
          console.error('Error fetching dropdown data:', error)
        })
    },
    getData() {
      // 在这里可以使用选定的值:this.reason, this.condition, this.incidentType
      // 执行进一步的操作或 API 调用
      console.log('Selected Reason:', this.reason);
      console.log('Selected Condition:', this.condition);
      console.log('Selected Incident Type:', this.incidentType);
    }
  }
}
</script>

注意:

注意事项与最佳实践

  1. API 响应结构的重要性: 在开始前端开发之前,务必通过浏览器开发者工具的网络标签页或使用工具(如 Postman、Insomnia)仔细检查 API 返回的实际数据结构。这是理解如何处理数据的首要步骤。
  2. 数据转换的必要性: 前端 UI 组件的显示需求与后端数据结构不一致是常态。前端数据转换(也称为数据整形或数据映射)是构建健壮应用的关键环节。
  3. J*aScript Set 的妙用: 当你需要从一个列表中获取所有唯一值时,Set 提供了一种非常简洁和高效的方法。它比手动遍历数组并检查是否存在重复项要高效得多。
  4. Vue 的响应性: 确保你正确地更新了 Vue 组件的 data 属性。直接修改 this.dropdownData 会触发 Vue 的响应式系统,从而更新视图。
  5. 错误处理: 在 fetch 请求中始终包含 .catch() 块来处理网络错误或 API 返回的非成功状态码,这对于用户体验和调试至关重要。

总结

在 Vue 3 应用中,从 Fetch API 获取数据并动态填充下拉菜单是一个常见的任务。解决数据无法正确填充的问题,关键在于理解 API 返回的原始数据结构,并利用 J*aScript 提供的强大工具(如 Array.prototype.map() 和 Set)对数据进行有效的转换和去重。通过这种方式,我们可以将复杂的原始数据转化为 UI 组件所需的简洁、唯一的选项列表,从而构建出功能完善且用户友好的应用程序。灵活处理数据是 Vue 3 开发中构建健壮应用的关键能力之一。

以上就是Vue 3 中使用 Fetch API 处理复杂数据并动态填充下拉菜单的实践的详细内容,更多请关注其它相关文章!

本文转自网络,如有侵权请联系客服删除。