簡體   English   中英

Vue-Select 無法從數組創建選項

[英]Vue-Select is Unable to Create Options from an Array

我是一名初學者,目前正在學習 Vue 和 Nuxt JS,並使用 Nuxt JS 開發一個簡單的 Web 應用程序。 目前,我正在嘗試制作一個 Vue Select 選項,其中我傳遞一個數組,並且我的選項是數組中的元素。 這是我當前的 index.vue(TextBox 和 DropDown 是我定義的組件):

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

當我運行這段代碼時,它編譯成功,但是控制台給了我以下警告:

 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>

本地主機視圖顯示:

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

我嘗試過改變一些事情,比如在 created() 或 mount() 下移動數組而不是 data() 並使數據成為變量列表而不是返回變量的函數,但無論我嘗試什么,Vue-select 仍然無法訪問國家/地區的數組,所以我不確定發生了什么。

v-for指令前不帶分號。 刪除它,您將克服該錯誤。

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

您還應該為v-for迭代中的任何元素添加一個唯一的:key 並且為了明確起見,您可以添加一個value道具來指示選擇時將使用哪個字段。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM