Vue与Laravel中下拉框change事件获取数据异常求助
解决b-form-select change事件的TypeError问题
首先咱们定位核心问题:Bootstrap-Vue的<b-form-select>组件的@change事件传递的不是原生DOM事件对象,而是选中的选项值本身。你原来的代码里试图访问e.target.value,但这里的e已经是选中的tipo值了,自然找不到target属性,所以才会报Cannot read property 'target' of undefined的错误。
接下来咱们一步步修正:
1. 修正Vue的change事件处理方法
把selecionar方法里的参数逻辑改对,同时修复Axios请求的URL拼接错误(你原来的参数格式不符合Laravel的接收规则):
selecionar(selectedTipo){ // selectedTipo就是下拉框选中的值,直接使用即可 const tipo = parseInt(selectedTipo); const url = this.rotatipoautcomp; // 正确拼接URL参数:?tipo=xxx,让Laravel能识别到参数名 axios.get(`${url}?tipo=${tipo}`) .then(res => { this.manutencoes = res.data; console.log(tipo); // parseInt是全局方法,不用加this }) .catch(err => { // 建议新增错误捕获,方便调试请求问题 console.error('请求失败:', err); }); }
2. 调整Vue模板的事件绑定
模板里的@change无需手动传$e,组件默认会把选中值作为第一个参数传递给方法:
<b-col md="4" sm="12"> <b-form-group label="Tipo: " label-for="tipo"> <input type="hidden" v-model="maintenance.typeId" name="tipoId" id="tipoId"> <b-form-select id="tipo" :options="options" :readonly="mode === 'remove'" @change="selecionar" <!-- 直接绑定方法名即可 --> ></b-form-select> </b-form-group> </b-col>
3. 优化Laravel控制器的参数获取
推荐用$request对象来获取参数,更符合Laravel的现代写法,同时增加默认值避免参数不存在的情况:
use Illuminate\Http\Request; public function ajaxServices(Request $request) { // 从request获取tipo参数,第二个参数是默认值,防止参数为空 $tipo = $request->input('tipo', 0); $tiposSelected = TecManutencaoTipo::select('manutencao AS value') ->where('tipo', '=', $tipo) ->get(); // 无需复杂判断,直接返回数据即可,空结果会返回空数组 return response()->json($tiposSelected); }
额外调试小技巧
- 在
selecionar方法开头加console.log(selectedTipo),确认拿到的是预期的下拉框值; - 在Laravel控制器里用
\Log::info($tipo)记录接收的参数,验证是否和前端传递的值一致; - 打印
this.rotatipoautcomp确认路由URL是否正确,比如是否指向了ajax-tipo的地址。
内容的提问来源于stack exchange,提问作者Gabriel Sassaki
相关产品推荐
相关产品推荐

