我无法在select选项中显示国家列表:属性未定义的错误提示



我一直在使用简单的下拉菜单,并且我一直有这个错误返回https://prnt.sc/1xdusd2(我解决了prop问题)

然后我阅读了更多关于这个特定问题的信息,结果发现当vue实例无法找到您的属性时,会发生这种情况。

国家,存在,并且在实例内。我不明白我哪里出错了。

因此,我们的想法是使下拉菜单响应我从api获得的国家数据。

数据只存在于父组件上,我将它作为道具发送给子组件,在那里我迭代并在选项中显示。

有谁能告诉我这里到底出了什么问题

drop down component (child component) 

<template>
<div>
<select v-for="(country, ) in countries" :key="country">
<option >{{country.name}} </option>
</select>
</div>
</template>
<script>
export default {
name: "DropDown",
props:['countries'],
data() {
return {
selectedOption: null,
};
},
};
</script>

parent component ************
<template>
<div class="step1 flex flex-col">
<h1 class="self-start mb-5">Шаг 1.</h1>
<div class="flex justify-center ">
<h3 class="text-white font-medium text-xl">Выберите страну</h3>
<div class="mx-5" >
<DropDown :countries="countries" />
{{}}
</div>
</div>
</div>
</template>
<script>
//import Button from "./UI/Button.vue";
import DropDown from "./UI/DropDown.vue";
export default {
name: "Step1",
components: {
DropDown: DropDown,
//Button: Button,
},

data() {
return{
// countries: [
//   {
//       id: "RU",
//       name: "Россия"
//   },
//   {
//       id: "DE",
//       name: "Германия"
//   },
//   {
//       id: "EE",
//       name: "Эстония"
//   }
// ],
}
},
methods:{
async fetchCountry (){
const res = await fetch('api/countries')
let countries = await res.json();
return countries
}
},
created() {

}
};

Vue尝试在api获取完成之前加载您的国家/地区数据,为了绕过此,在您的<select v-for="(country, ) in countries" :key="country">中添加v-if="countries",然后Vue只会尝试加载它,如果国家/地区不为空

你需要在你的数据中有国家,以便它在模板中工作,在你的父元素中试试:

import DropDown from "./UI/DropDown.vue";
export default {
name: "Step1",
components: {
DropDown,
},

data() {
return {
countries: [],
}
},
methods: {
async fetchCountry() {
const res = await fetch('api/countries')
this.countries = await res.json();
}
},
};

在你的孩子身上

<template>
<select v-model="selectedOption">
<option
v-for="country in countries"
:key="country.name"
:value="country.name"
>
{{ country.name }}
</option>
</select>
</template>
<script>
export default {
name: "DropDown",
props: {
countries: {
type: Array,
default: () => [],
},
},
data() {
return {
selectedOption: null,
};
},
};
</script>

最新更新