我正在使用 VueSelect 进行地址选择。国家、州、城市有 3 个选择组件。
使用 v-model 时,使用 reduce prop 获取指定值而不是选项对象效果很好。这里我的问题是不按键值设置默认值。
我希望它像 html select 一样通过 id 设置默认值。但它按原样显示键值,不受标签值的约束。
希望你能从我的解释中理解。
期待像 vuetify 的 v-select。
验证示例
<template>
<div class="col-sm-6 ">
<v-select
v-model="address.country_id"
:options="countryOptions"
:reduce="country => country.id"
label="name"
@input="resetStateAndCity"
:resetOnOptionsChange="true"
/>
</div>
<div class="col-sm-6">
<v-select
v-model="address.state_id"
:options="stateOptions"
:reduce="state => state.id"
label="name"
@input="resetCity"
:resetOnOptionsChange="true"
/>
</div>
<div class="col-sm-6">
<v-select
v-model="address.city_id"
:options="cityOptions"
:reduce="city => city.id"
label="name"
:resetOnOptionsChange="true"
/>
</div>
</template>
<script>
import VSelect from 'vue-select'
export default {
components: {
VSelect
},
data: function () {
return {
address: {
city_id: null,
state_id: null,
country_id: null
},
countryOptions: [],
stateOptions: [],
cityOptions: []
}
},
mounted() {
this.$axios.get('/countries.json')
.then(response => {
this.countryOptions = response.data
})
},
methods: {
resetStateAndCity() {
if (!this.address.country_id) return
this.$axios.get(`/countries/${this.address.country_id}/states.json`)
.then(response => {
this.stateOptions = response.data
})
this.address.state_id = null
this.address.city_id = null
this.cityOptions = []
},
resetCity() {
if (!this.address.country_id || !this.address.state_id) return
this.address.city_id = null
this.$axios.get(`/countries/${this.address.country_id}/states/${this.address.state_id}/cities.json`)
.then(response => {
this.cityOptions = response.data
})
}
}
}
</script>