【问题标题】:Vue-Select is Unable to Create Options from an ArrayVue-Select 无法从数组创建选项
【发布时间】:2022-07-14 14:00:42
【问题描述】:

我是一名初学者,目前正在学习 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() 或 mounted() 下而不是 data() 并将数据设为变量列表而不是返回变量的函数,但无论我尝试什么,Vue- select 仍然无法访问国家/地区数组,所以我不确定发生了什么。

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js vue-select


    【解决方案1】:

    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>
    

    【讨论】:

    • 太棒了,成功了!感谢您的帮助。
    猜你喜欢
    • 2019-12-21
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 2021-02-09
    • 2023-04-03
    • 2021-11-02
    相关资源
    最近更新 更多