在写地址选择器时,选择省份显示对应的城市,监听省份和城市的变化,代码如下,主要研究watch
<script>
import { defineComponent, reactive, toRefs, watch } from "vue";
export default defineComponent({
setup(props, { emit }) {
const state = reactive({
province: '',
country: '',
detailedAdress: '',
countries: [],
allCity: [],
});
watch(() => state.province, () => {
const arr = state.allCity.filter((item) => item.province == state.province);
console.log(arr);
state.countries = arr[0].cities;
state.country = "";
state.detailedAdress = "";
console.log(state.countries);
}
);
watch(() => state.country, () => {
state.detailedAdress = "";
console.log(state.countries);
}
);
watch(() => [state.province, state.country], ([newprovince,newcountry],[oldprovince,oldcountry]) => {
console.log(oldprovince,'省份---', newprovince);
console.log(newcountry,'cs---', oldcountry);
if(oldprovince !== newprovince) {
const arr = state.allCity.filter((item) => item.province == state.province);
state.countries = arr[0].cities;
console.log(arr);
state.country = "";
}
state.detailedAdress = "";
console.log(state.countries);
}
);
return {
...toRefs(state),
};
},
});
</script>
如有问题请评论,谢谢,希望可以帮到有需要的人
|