gpt4 book ai didi

javascript - 重置 VueJS 中的先前选择

转载 作者:搜寻专家 更新时间:2023-10-30 22:37:35 25 4
gpt4 key购买 nike

我有两个 custom select input表单中的字段:CountryCity。正如您可能已经猜到的那样,城市取决于国家/地区。因此,当用户选择一个国家/地区时:

  • 执行 ajax 调用
  • 获取所选国家/地区的城市
  • 获取的城市显示在第二个选择框中

场景:在国家/地区选择框中,我选择了美国。从城市选择框中,我选择了 Texas(其值为: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>

每次选择国家/地区时如何重置城市选择?

最佳答案

问题是 Vue 试图重用现有的 HTML 以加速渲染。在您的情况下,它选择不为选择框重新呈现 HTML,它只是更改选项的文本内容。强制重新渲染的简单方法是根据所选国家/地区使用不同的关键 Prop 进行城市选择:

<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" 添加到城市选择中。您需要在 selectCountry 方法中创建此 selectedCountryId 属性,例如:

selectCountry (e) {
this.selectedCountryId = e.target.selectedIndex
axios.get(...)
}

关于javascript - 重置 VueJS 中的先前选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084796/

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