Select 组件如何动态更新选项?

我需要用 Select 组件做一个城市选择的功能,想让它的选项根据用户选择的国家动态更新,但不知道如何实现动态更新的效果。有没有朋友可以给个代码示例,帮我理解一下如何绑定和更新数据?

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

阅读 547
1 个回答

可以通过将选项数据绑定到 Select 组件的 range 属性,并通过事件来动态更新这些数据。

export default {
  data: {
    countries: ['中国', '美国', '英国'],
    cities: {
      '中国': ['北京', '上海', '广州'],
      '美国': ['纽约', '洛杉矶'],
      '英国': ['伦敦', '曼彻斯特'],
    },
    selectedCountry: '中国',
    availableCities: []
  },
  onInit() {
    this.updateCities('中国');
  },
  updateCities(country) {
    this.availableCities = this.cities[country];
  },
  onCountryChange(index) {
    this.selectedCountry = this.countries[index];
    this.updateCities(this.selectedCountry);
  }
}
<Select range="{{countries}}" onChange="onCountryChange"></Select>
<Select range="{{availableCities}}"></Select>

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

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