Vue3 Fetch 获取数据但不填充下拉字段。 :( 我做错了什么?

huangapple go评论72阅读模式
英文:

Vue3 Fetch getting data but not populating dropdown fields. Vue3 Fetch 获取数据但不填充下拉字段。 :( 我做错了什么? What am I doing wrong?

问题

我已创建了一个公司,试图从北卡罗来纳州获取事故数据,以便我可以将其显示在地图上。然而,虽然正在下载数据(418条记录),但它没有将其拆分成适当的部分,以便在选择/选项下拉菜单中呈现。我不确定为什么会发生这种情况。我已经思考了至少一个小时,但无论是询问ChaT GPT还是在Stack Overflow上进行了大量查找,都没有得到任何运气。

期望输出:下拉菜单填充数据
实际输出:下拉菜单但没有数据,然而调用结果为418条记录,所以?

有人有什么见解吗?非常感谢。

<template>
  <div>
    <div>要知道{{ dropdownData }}</div>
    <select v-model="reason">
      <option v-for="r in dropdownData.reasons" :value="r">{{ r }}</option>
    </select>
    <select v-model="condition">
      <option v-for="c in dropdownData.conditions" :value="c">{{ c }}</option>
    </select>
    <select v-model="incidentType">
      <option v-for="type in dropdownData.incidentTypes" :value="type">{{ type }}</option>
    </select>
    <button @click="getData">获取数据</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('网络响应不正常')
          }
          return response.json()
        })
        .then((data) => {
          // 使用Vue.set或展开运算符创建一个新的响应式对象
          this.dropdownData = {
            reasons: [...data.reasons],
            conditions: [...data.conditions],
            incidentTypes: [...data.incidentTypes]
          }
        })
        .catch((error) => {
          // 处理错误
          console.error('错误:', error)
        })
    },
    getData() {
      // 使用选定的值:this.reason,this.condition,this.incidentType
      // 基于选定的值执行进一步的操作或API调用
    }
  }
}
</script>

思路?

以下是Cody提出的一些建议,但我认为它们可能不适用,除了可能是第7条,但我还是想分享一下。

可能导致选择选项不填充的几个可能原因:

  1. dropdownData 对象为空。如果用于填充数据的API调用尚未完成或失败,则dropdownData 将为空,不会呈现任何选项。

  2. v-for指令正在迭代空数组。如果 dropdownData.reasonsdropdownData.conditionsdropdownData.incidentTypes 为空数组,则不会呈现选项。

  3. 模板中存在语法错误,阻止其编译。仔细检查所有v-for指令、v-model等是否具有正确的语法。

  4. 数据函数没有返回dropdownData 对象。确保 data() 返回 dropdownData,并且它不是未定义的。

  5. 在挂载的生命周期钩子中存在错误,阻止API调用完成。检查网络选项卡以查看API调用是否失败,并仔细检查挂载函数中的任何错误。

  6. select元素具有v-model,但选项的值未设置。要使v-model工作,每个选项必须设置一个值属性。

  7. 组件实际上没有使用dropdownData 数据。确保v-for正在迭代dropdownData,并且v-model正在使用dropdownData 中的数据。

英文:

I have created a company to try to download incident data from the North Carolina determine the transportation so that I can put it on a map. However, while it is downloading the data (418 records), it is not splitting it up into the appropriate sections so that it can be rendered in the select/option drop downs. I am not sure why this is not happening. I've been noodling on this for at least an hour and I just have not been getting any luck regardless of asking ChaT GPT, and doing a lot of look on Stack Overflow, etc.

INPUT: https://eapps.ncdot.gov/services/traffic-prod/v1/incidents
EXPECTED OUTPUT: Dropdowns populated with data
ACTUAL: Dropdowns but no data, however call resuls in 418 records, so?

Anyone have any insights? Much appreciated.

    &lt;template&gt;
&lt;div&gt;
&lt;div&gt;to wit: {{ dropdownData }}&lt;/div&gt;
&lt;select v-model=&quot;reason&quot;&gt;
&lt;option v-for=&quot;r in dropdownData.reasons&quot; :value=&quot;r&quot;&gt;{{ r }}&lt;/option&gt;
&lt;/select&gt;
&lt;select v-model=&quot;condition&quot;&gt;
&lt;option v-for=&quot;c in dropdownData.conditions&quot; :value=&quot;c&quot;&gt;{{ c }}&lt;/option&gt;
&lt;/select&gt;
&lt;select v-model=&quot;incidentType&quot;&gt;
&lt;option v-for=&quot;type in dropdownData.incidentTypes&quot; :value=&quot;type&quot;&gt;{{ type }}&lt;/option&gt;
&lt;/select&gt;
&lt;button @click=&quot;getData&quot;&gt;Get Data&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
data() {
return {
reason: null,
condition: null,
incidentType: null,
dropdownData: {
reasons: [],
conditions: [],
incidentTypes: []
}
}
},
mounted() {
this.fetchDropdownData()
},
methods: {
fetchDropdownData() {
// actual API: https://eapps.ncdot.gov/services/traffic-prod/v1/incidents?verbose=true
fetch(`${import.meta.env.VITE_API_VERBOSE}`)
.then((response) =&gt; {
if (!response.ok) {
throw new Error(&#39;Network response was not ok&#39;)
}
return response.json()
})
.then((data) =&gt; {
// Create a new reactive object using Vue.set or spread operator
this.dropdownData = {
reasons: [...data.reasons],
conditions: [...data.conditions],
incidentTypes: [...data.incidentTypes]
}
})
.catch((error) =&gt; {
// Handle error
console.error(&#39;Error:&#39;, error)
})
},
getData() {
// Make use of the selected values: this.reason, this.condition, this.incidentType
// Perform further operations or API calls based on the selected values
}
}
}
&lt;/script&gt;

Codepen: https://codepen.io/MaxRocket/pen/wvYVKJY

Thoughts?

Here are a few suggestions from Cody, but I don't think they apply, except maybe #7, but I thought I'd share them anyway.

There are a few possible reasons the select options may not be populating:

  1. The dropdownData object is empty. If the API call to populate the
    data has not completed or failed, dropdownData will be empty and no options will render.

  2. The v-for directive is iterating over an empty array. If
    dropdownData.reasons, dropdownData.conditions, or
    dropdownData.incidentTypes are empty arrays, no options will be
    rendered.

  3. There is a syntax error in the template preventing it from
    compiling. Double check that all v-for directives, v-models, etc.
    have correct syntax.

  4. The data function is not returning the dropdownData object. Make
    sure data() returns dropdownData, and that it is not undefined.

  5. There is an error in the mounted lifecycle hook preventing the API
    call from completing. Check the network tab to see if the API call
    is failing, and double check for any errors in the mounted function.

  6. The select element has a v-model but no value set for the options.
    For a v-model to work, each must have a value attribute set.

  7. The component is not actually using the dropdownData data. Make sure
    v-for is iterating over dropdownData, and v-model is using the data
    from dropdownData.

答案1

得分: 4

问题在于这段代码:

reasons: [...data.reasons],
conditions: [...data.conditions],
incidentTypes: [...data.incidentTypes]

你的数据返回一个包含项目的数组,每个项目都有属性,如reason(原因)、condition(条件)和incidentType(事故类型)。你应该根据这些项目创建一个数组。例如:

reasons: data.map(el => el.reason),
conditions: data.map(el => el.condition),
incidentTypes: data.map(el => el.incidentType)
英文:

The problem is this code

reasons: [...data.reasons],
conditions: [...data.conditions],
incidentTypes: [...data.incidentTypes]

Your data returns an array of item, in each item has properties like reason, condition and incidentType. You should create an array base on that items. For example

 reasons: data.map(el =&gt; el.reason),
conditions: data.map(el =&gt; el.condition),
ncidentTypes: data.map(el =&gt;el.incidentType)

答案2

得分: 1

我已经在你的CodePen中尝试了以下内容:

getData() {
  // 利用选定的数值:this.reason, this.condition, this.incidentType
  // 根据选定的数值执行进一步的操作或API调用
  const testData = { reasons: ['reason1, reason2'], conditions: ['condition1, condition2'], incidentTypes: ['incidentTypes1, incidentTypes2'] }
  // 使用Vue.set或扩展运算符创建一个新的响应式对象
  this.dropdownData = {
    reasons: [...testData.reasons],
    conditions: [...testData.conditions],
    incidentTypes: [...testData.incidentTypes]
  }
}

然后,当我点击"获取数据"按钮时,它可以正常工作。

你能提供console.log('data: ', data);的结果吗?这可能与你从调用中收到的结果有关。

英文:

I have tried the following in your codepen:

getData() {
      // Make use of the selected values: this.reason, this.condition, this.incidentType
      // Perform further operations or API calls based on the selected values
      const testData = { reasons: [&#39;reason1, reason2&#39;], conditions: [&#39;condition1, condition2&#39;], incidentTypes: [&#39;incidentTypes1, incidentTypes2&#39;] }
      // Create a new reactive object using Vue.set or spread operator
      this.dropdownData = {
        reasons: [...testData.reasons],
        conditions: [...testData.conditions],
        incidentTypes: [...testData.incidentTypes]
      }
    }

Then, when I click the button for Get Data, it works like a charm.

Can you provide us with the results of console.log(&#39;data: &#39;, data); ? It might be an issue with the results you receive from the call.

huangapple
  • 本文由 发表于 2023年6月2日 07:56:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定