目标
架构
vue+ts
前端
#ProvinceCitySelector.vue
<template>
<div>
<label>省份:</label>
<select v-model="selectedProvince" @change="fetchCities">
<option value="">请选择</option>
<option v-for="province in provinces" :key="province.id" :value="province.id">
{{ province.name }}
</option>
</select>
<label>城市:</label>
<select v-model="selectedCity">
<option value="">请选择</option>
<option v-for="city in cities" :key="city.id" :value="city.id">
{{ city.name }}
</option>
</select>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import axios from 'axios';
export default defineComponent({
name: 'ProvinceCitySelector',
setup() {
const provinces = ref<{ id: number; name: string }[]>([]);
const cities = ref<{ id: number; name: string }[]>([]);
const selectedProvince = ref('');
const selectedCity = ref('');
// 获取省份列表
const fetchProvinces = async () => {
try {
const response = await axios.get('http://localhost:3000/api/provinces');
provinces.value = response.data;
} catch (error) {
console.error("Error fetching provinces:", error);
}
};
// 获取选中省份的城市列表
const fetchCities = async () => {
if (selectedProvince.value) {
try {
const response = await axios.get(`http://localhost:3000/api/cities?provinceId=${selectedProvince.value}`);
cities.value = response.data;
} catch (error) {
console.error("Error fetching cities:", error);
}
} else {
cities.value = [];
}
};
// 初始加载省份
fetchProvinces();
return {
provinces,
cities,
selectedProvince,
selectedCity,
fetchCities,
};
}
});
</script>
<style scoped>
select {
margin: 0 10px;
}
</style>
后端
#server.js
// server.js
import express from 'express';
import cors from 'cors';
const app = express();
const port = 3000;
// 允许跨域请求
app.use(cors());
// 模拟数据库数据
const provinces = [
{ id: 1, name: "四川" },
{ id: 2, name: "广东" },
{ id: 3, name: "浙江" }
];
const cities = {
1: [
{ id: 101, name: "成都" },
{ id: 102, name: "绵阳" },
{ id: 103, name: "德阳" }
],
2: [
{ id: 201, name: "广州" },
{ id: 202, name: "深圳" },
{ id: 203, name: "珠海" }
],
3: [
{ id: 301, name: "杭州" },
{ id: 302, name: "宁波" },
{ id: 303, name: "温州" }
]
};
// 获取省份列表
app.get('/api/provinces', (req, res) => {
res.json(provinces);
});
// 根据省份 ID 获取城市列表
app.get('/api/cities', (req, res) => {
const provinceId = req.query.provinceId;
const cityList = cities[provinceId];
if (cityList) {
res.json(cityList);
} else {
res.status(404).json({ message: "省份ID未找到对应的城市" });
}
});
// 启动服务器
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});