在写地址选择器时,选择省份显示对应的城市,监听省份和城市的变化,代码如下,主要研究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太麻烦,现用watch监听省份和城市两个数据
// 第一个参数() => [state.province, state.country] 监听的两个数据
// 第二个参数回调函数,其中参数分别代表更改后与更改前的值,([newprovince,newcountry],[oldprovince,oldcountry]) ,第一个参数依次代表更改后的值,第二个参数依次代表更改前的值
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>
如有问题请评论,谢谢,希望可以帮到有需要的人