[Vuejs]-I cannot display the list of countries within the select option: property undefined error vuejs

0👍

Vue tries to load your country data before the api fetch has finished, to bypass this add an v-if="countries" in your <select v-for="(country, ) in countries" :key="country">, then vue will only try to load it if countries is not null

0👍

You need to have countries in your data in order for it to work in the template, try this in your parent:

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

And this in your child

<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>

Leave a comment