表单联动时如何让子组件正确响应父组件的值变化?

西门曌煜 阅读 8

我在用 Vue 写一个动态表单,父组件里有个下拉框选“国家”,子组件要根据选中的国家动态加载“城市”选项。但子组件的 props 虽然能收到新值,watch 却不触发,数据没更新。

我试过在子组件里用 watch: { country(newVal) { ... } },也试过加 immediate: true,但第一次选完之后再切换国家就没反应了。是不是哪里写错了?

export default {
  props: ['country'],
  data() {
    return { cities: [] }
  },
  watch: {
    country(newVal) {
      if (newVal) {
        this.cities = fetchCitiesByCountry(newVal); // 伪代码
      }
    }
  }
}
我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
Mc.子斌
Mc.子斌 Lv1
fetchCitiesByCountry 需要返回 Promise,然后用 then 处理结果。这样改:
watch: {
country(newVal) {
if (newVal) {
fetchCitiesByCountry(newVal).then(cities => this.cities = cities);
}
}
}

就这样
点赞
2026-03-21 17:00