You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js报property undefined错误 下拉选择框无法显示国家列表

问题排查结果

你的代码存在以下5个明确问题:

  • 父组件未在data中声明countries响应式属性:你注释了默认的测试数据后,没有保留countries: []的初始声明,Vue无法识别该响应式变量,自然会报属性不存在的错误
  • 父组件从未调用接口获取数据:fetchCountry方法没有在created钩子中触发,接口请求根本不会执行
  • 子组件循环位置错误:你把v-for写在了<select>标签上,会渲染出多个下拉框,正确做法是把v-for写在<option>标签上,仅渲染多个选项
  • 子组件v-for的key值非法:你直接用对象作为key,Vue要求key必须是字符串/数字这类基础类型,应该用每个国家唯一的id字段作为key
  • 父组件模板存在空插值语法:{{}}属于非法语法,会直接触发报错

修复后代码

子组件(DropDown.vue)

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

父组件(Step1.vue)

<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 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();
    }
  },

  created() {
    this.fetchCountry()
  }
};
</script>

内容的提问来源于stack exchange,提问作者Eternal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:30:03