表单联动时如何让子组件正确响应父组件的值变化?
我在用 Vue 写一个动态表单,父组件里有个下拉框选“国家”,子组件要根据选中的国家动态加载“城市”选项。但子组件的 props 虽然能收到新值,watch 却不触发,数据没更新。
我试过在子组件里用 watch: { country(newVal) { ... } },也试过加 immediate: true,但第一次选完之后再切换国家就没反应了。是不是哪里写错了?
export default {
props: ['country'],
data() {
return { cities: [] }
},
watch: {
country(newVal) {
if (newVal) {
this.cities = fetchCitiesByCountry(newVal); // 伪代码
}
}
}
}
就这样