Skip to content
Advertisement

Vue-Select is Unable to Create Options from an Array

I am a beginner who is currently learning Vue and Nuxt JS and developing a simple web application with Nuxt JS. Currently, I am trying to make a Vue Select option where I pass an array and I have the options be the elements in the array. This is my current index.vue (TextBox and DropDown are components I have defined):

<template>
  <body>
    <div id = "app">
      <select v-model="selected">
        <option :v-for="country in countries">{{ country.countryName }}</option>
      </select>
      <br/>
      <TextBox label = "Name of new country:"/>
      <TextBox label = "Code of new country:"/>
      <button>Submit</button>
      <br/>
      <br/>
      <TextBox label = "Name of new state/province:"/>
      <TextBox label = "Code of new state/province:"/>
      <DropDown label = "Countries of this state/province"/>

    </div>
  </body>
</template>

<script>
export default {
  name: 'IndexPage',
  data() {
    return {
      selected: "",
      countries: [{"countryName":"Canada"}, {"countryName":"US"}, {"countryName":"UK"}, {"countryName":"France"}]
    };
  },

}
</script>

When I run this code, it compiles successfully, but then the console gives me the following warning:

 ERROR  [Vue warn]: Property or method "country" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <IndexPage> at pages/index.vue
       <Nuxt>
         <.nuxt/layouts/default.vue> at .nuxt/layouts/default.vue
           <Root>

And the localhost view displays:

TypeError
Cannot read properties of undefined (reading 'countryName')

I have tried changing things like moving the array under created() or mounted() instead of data() and making data a list of variables instead of a function that returns variables, but no matter what I try, the Vue-select is still unable to access the array of countries, so I’m not sure what is happening.

Advertisement

Answer

v-for doesn’t take a semicolon before the directive. Remove that and you’ll get past that error.

    <select v-model="selected">
      <option v-for="country in countries">{{ country.countryName }}</option>
    </select>

You should also add a unique :key to any element in a v-for iteration. And for being-explicit’s sake, you can add a value prop to indicate which field will be used when selected.

    <select v-model="selected">
      <option v-for="country in countries" :key="country.countryName" :value="country.countryName">
        {{ country.countryName }}
      </option>
    </select>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement