在Vue.js中如何通过REST API实现下拉选择框的数据加载?
Vue级联下拉对接国家/城市API实现方案
代码调整说明
1. 新增请求依赖
如果项目还没集成请求工具,先在HTML的<head>中引入axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2. 修改核心JS逻辑
调整后的完整Vue实例代码如下,原HTML、CSS代码无需改动即可兼容:
// 全局配置请求头,统一注入认证信息 axios.defaults.headers.common['Authorization'] = 'Bearer IIPwMXygilaKrQJfNLuj-LHZWn5kxBVZRLJ-KtU5jxRivdTBkHio6IOyF60CERyOPjo' axios.defaults.headers.common['Accept'] = 'application/json' new Vue({ el: '#app', data: function() { return { // 按大洲分组的国家数据,替代原本地静态places对象 places: {}, countries: [], cities: [], selectedContinent: "", selectedCountry: "", selectedCity: "" } }, mounted() { // 页面初始化时拉取全量国家数据,按大洲分组 axios.get('https://www.universal-tutorial.com/api/countries') .then(res => { const countryList = res.data countryList.forEach(item => { if (!this.places[item.continent]) { this.places[item.continent] = {} } // 预留国家对应州/省的存储位置,后续请求动态填充 this.places[item.continent][item.country_name] = [] }) }) .catch(err => { console.error('国家列表获取失败:', err) }) }, watch: { selectedContinent: function() { // 清空原有下级选中值和列表 this.countries = []; this.cities = []; this.selectedCountry = ""; this.selectedCity = ""; if (this.selectedContinent.length > 0) { this.countries = this.places[this.selectedContinent] } }, selectedCountry: function() { this.cities = []; this.selectedCity = ""; if (this.selectedCountry.length > 0) { // 动态拉取当前国家对应的州/省列表 axios.get(`https://www.universal-tutorial.com/api/states/${this.selectedCountry}`) .then(res => { const stateList = res.data.map(item => item.state_name) this.places[this.selectedContinent][this.selectedCountry] = stateList this.cities = stateList }) .catch(err => { console.error('州/省列表获取失败:', err) }) } } } })
3. 注意事项
- 跨域问题:本地测试出现跨域报错时,可临时用浏览器跨域插件解决,生产环境需要配置服务端代理转发请求
- 令牌有效期:当前提供的访问令牌存在有效时长限制,失效后需要重新生成替换代码中的令牌值
- 如果不需要保留大洲层级,可直接把第一级下拉改为国家选择,省略按大洲分组的逻辑,代码会更精简
内容的提问来源于stack exchange,提问作者T dhanunjay
相关产品推荐
相关产品推荐

