gpt4 book ai didi

Vue.js 选择的选项不是基于值

转载 作者:行者123 更新时间:2023-12-04 03:38:20 25 4
gpt4 key购买 nike

我有一个从这样的 API 调用返回的 json 对象:

"countries": [
{
"id": 1,
"iso": US,
"name": "United States",
},
{
"id": 2,
"iso": FR,
"name": "France",
},
{
"id": 3,
"iso": GB,
"name": "United Kingdom",
},
]

在我的 vue 组件中:

<select v-model="country">
<option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>

如何根据 iso 代码预先选择第三个 json 实例?

v-for 中的以下代码不起作用

:selected="country.iso === 'GB'"

我当然可以

data: function () {
country: 3
}

但我想根据 iso 代码而不是 id 声明默认选择值。

我不想将 iso 更改为模型的值,因为我要将它作为 post 请求发送到我的 API。如果这样做,我可以解析整个 json 对象以从其 iso 代码中找到 id,但我不确定这是否是最干净的解决方案。

谢谢

最佳答案

您可以在 API 调用后执行此操作,我猜您在 mounted() 中有它, 然后把你需要的值放在 country 中值(value)。

像这样:

mounted() {
axios.get('your-api-call-for-countries').then(response => {
// Assign data from ...
this.countries = response
// Find Object which you want to be pre selected...
let selected = this.countries.find(i => i.iso === 'GB')
// Use id for your v-model...
this.country = selected.id

// or simplier
this.country = this.countries.find(i => i.iso === 'GB').id
})
}

我认为这是唯一的解决方案,因为您需要 id基于 iso .

关于Vue.js 选择的选项不是基于值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66515463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com