在寫位址選擇器時,選擇省份顯示對應的城市,監聽省份和城市的變化,代碼如下,主要研究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>
如有問題請評論,謝謝,希望可以幫到有需要的人