始终选择第一个值选择 vue.js

新手上路,请多包涵

我如何始终使用选择(在 vue.js 中)选择第一个项目?

 <div class="ride-item-content">
  <select v-model="ride.location_id">
    <option v-for="location in locations" v-bind:value="location.id">
      {{ location.from }} - {{ location.to }}
    </option>
  </select>
</div>

JSON

 {
  "locations": {
    "total": 2,
    "per_page": 20,
    "current_page": 1,
    "last_page": 1,
    "next_page_url": null,
    "prev_page_url": null,
    "from": 1,
    "to": 2,
    "data": [
      {
        "id": 1,
        "user_id": 1,
        "description": "sdg",
        "from": "asdf",
        "to": "asdf",
        "kmz": "12",
        "kmp": "13",
        "time": 0,
        "hour": 0,
        "maps": "www.blablabla.nl",
        "created_at": null,
        "updated_at": null
      },
      {
        "id": 2,
        "user_id": 1,
        "description": "asdf",
        "from": "asdf",
        "to": "asdf",
        "kmz": "3",
        "kmp": "1",
        "time": 1,
        "hour": 0,
        "maps": "www.test.nl",
        "created_at": null,
        "updated_at": null
      }
    ]
  }
}

- 编辑 -

<div class="ride-item-content">
  <select v-model="ride.location_id">
    <option v-for="location in locations" v-bind:selected="$index === 0 ? 'selected' : false">
      {{ location.from }} - {{ location.to }}
    </option>
  </select>
</div>

原文由 Jamie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 312
1 个回答

VueJS 1:

 <option v-for="location in locations" v-bind:value="location.id" v-bind:selected="$index === 0 ? 'selected' : false">
  {{ location.from }} - {{ location.to }}
</option>

VueJS 2:

 <option v-for="(location, index) in locations" v-bind:value="location.id" v-bind:selected="index === 0">
  {{ location.from }} - {{ location.to }}
</option>

在 Vue 1 中, $indexv-for 循环中自动可用。

在 Vue 2 中,您需要为索引显式声明一个变量。

原文由 J. Bruni 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题