Vue+Axios实现@click传参触发二次API调用获取车型列表失效问题
问题根因与修正实现
现存代码的核心错误
- 缺少响应式变量定义:
data配置中未声明用于存储选中品牌编码的brandSelected字段,Vue无法追踪该字段的状态变化,即使手动赋值也会因为非响应式特性导致后续读取异常 - 点击事件逻辑反向错误:
brandSelected方法内将存储全量品牌列表的this.brands数组直接赋值为单个品牌编码,直接覆盖已加载的品牌列表数据;同时方法内的alert引用了未定义的model变量,点击时直接触发报错,中断整个执行流 - 方法调用链完全断裂:封装好的
getBrand方法从未被任何逻辑触发,点击操作仅执行错误的赋值流程,根本不会发起车型接口请求 - 冗余无效代码:
mounted钩子中调用的this.getModels()从未在methods中定义,执行时会直接抛出未定义错误
修正后核心代码
const API_URL = "https://parallelum.com.br/fipe/api/v1/carros/marcas"; new Vue({ el: "#app", data() { return { brands: [], models: [], brandSelected: null, // 新增响应式变量存储选中的品牌编码 loading: true, errored: false, }; }, mounted() { this.getBrands(); }, methods: { async getBrands() { try { const response = await axios.get(API_URL) this.brands = response.data; } catch (error) { console.log(error); this.errored = true; } finally { this.loading = false; } }, async getBrand() { // 校验选中的品牌编码存在后再发请求 if (!this.brandSelected) return; try { const response = await axios.get( `https://parallelum.com.br/fipe/api/v1/carros/marcas/${this.brandSelected}/modelos` ) this.models = response.data.modelos; } catch (error) { console.log(error); } }, // 修正点击事件逻辑 brandSelected(brand) { // 将选中的品牌编码存入独立的响应式变量,不覆盖原有品牌列表 this.brandSelected = brand.codigo; // 触发车型接口请求 this.getBrand(); } }, });
模板修正说明
原有模板将v-for指令写在<tbody>标签上,不符合HTML渲染规范,调整为将遍历逻辑下沉到<tr>标签层,避免DOM结构异常:
<tbody> <tr v-for="(brand, index) in brands" :key="index"> <td>{{brand.nome}} com código {{brand.codigo}}</td> <td> <a @click="brandSelected(brand)" data-toggle="modal" data-target="#modelsModal" >Ver modelos</a> </td> </tr> </tbody>
内容的提问来源于stack exchange,提问作者Lucas Marra
相关产品推荐
相关产品推荐

