我在表单中有两个custom select input字段:国家/地区和城市。正如您可能已经猜到的那样,城市依赖于国家。因此,当用户选择国家/地区时:
场景:从国家/地区选择框中,我选择了美国。从城市选择框我选择德克萨斯州(其值为6)。现在,如果我回到第一个选择框并将国家/地区更改为英国,它将根据之前的选择自动选择第6个英国城市。
这是我正在做的事情:
<custom-select type="select" name="country_id" @change="selectCountry">
<option disabled selected>Choose a Country</option>
<option v-for="country in countries" :value="country.id">@{{ country.name }}</option>
</custom-select>
<custom-select type="select" name="city_id" @change="selectCity">
<option disabled selected>Choose a City</option>
<option v-for="city in cities" :value="city.id">@{{ city.name }}</option>
</custom-select>
每次选择国家/地区时如何重置城市选择?
答案 0 :(得分:3)
问题在于Vue尝试重用现有的HTML以加快渲染速度。在您的情况下,它选择不为选择框重新呈现HTML,它只是更改选项的文本内容。强制重新渲染的简单方法是根据所选国家/地区使用不同的关键道具进行城市选择:
<custom-select type="select" :key="selectedCountryId" name="city_id" @change="selectCity">
<option disabled selected>Choose a City</option>
<option v-for="city in cities" :value="city.id">@{{ city.name }}</option>
</custom-select>
注意,我在城市选择中添加了:key="selectedCountryId"
。您需要在selectedCountryId
方法中创建此selectCountry
属性,例如:
selectCountry (e) {
this.selectedCountryId = e.target.selectedIndex
axios.get(...)
}
答案 1 :(得分:0)
我将使用一个简单的例子来说明如何做到这一点:
您也可以see it in action by clicking here
<div id="app">
<select v-model="selectedState" @change="stateChanged">
<option :value="null">Select State</option>
<option
v-for="state in states"
:key="state.id"
:value="state.id"
>
{{state.text}}
</option>
</select>
<select v-model="selectedCity">
<option :value="null">Select City</option>
<option
v-for="city in citiesDependOnSelectedState"
:key="city.id"
:value="city.id"
>
{{city.text}}
</option>
</select>
</div>
new Vue({
el: "#app",
data: {
states: [
{ text: "Albania", id: 1 },
{ text: "Greece", id: 2 },
{ text: "Italy", id: 3 },
{ text: "Germany", id: 4 }
],
cities: [
{ text: "Tirana", id: 1, state: 1 },
{ text: "Vlora", id: 2, state: 1 },
{ text: "Thessaloniki", id: 3, state: 2 },
{ text: "Athens", id: 4, state: 2 },
{ text: "Berlin", id: 5, state: 4 },
{ text: "Hamburg", id: 6, state: 4 },
{ text: "Rome", id: 7, state: 3 },
{ text: "Milano", id: 8, state: 3 }
],
selectedState: null,
selectedCity: null
},
computed: {
citiesDependOnSelectedState() {
return this.cities.filter(el => el.state === this.selectedState)
}
},
methods: {
stateChanged() {
this.selectedCity = null
}
}
})