Laravel接口返回Transaction数据正常但Vue组件渲染为空且v-if判断失效
问题修复方案
1. 后端查询逻辑错误(核心问题)
需求为获取transactions表中account_id等于传入ID的关联交易数据,当前控制器代码查询的是交易表自身主键id等于传入ID,且仅返回单条数据,与需求完全不匹配。
修复后AccountsController代码:
public function show($id) { // 查询条件改为account_id,first()改为get()获取所有匹配记录 $show = Transaction::where('account_id', $id)->with(['account'])->get(); return response()->json($show); }
注:如果确实只需要单条匹配记录,保留
first()即可,仅修改查询条件字段为account_id。
2. Vue模板语法错误
v-if判断中写的=!为无效语法,实际执行逻辑为:先对字符串'sales'取反得到false,再赋值给data.attributes.transaction_type,会直接覆盖原有字段值,导致渲染为空且条件判断永远不生效。正确的不等于判断符为!==(严格不等)或!=(非严格不等)。
3. 响应数据结构适配调整
后端修改为返回多条交易数组后,Vue侧变量定义和渲染逻辑需要对应调整:
脚本部分修改
export default { data() { return { id: this.$route.params.id, data: { type: "transactions", attributes: [], // 从空对象改为空数组存储多条交易数据 }, } }, async created() { const res = await this.callApi('get', this.data.type + '/' + this.id) if (res.status === 200) { this.data.attributes = res.data; // 可在此处打印验证赋值结果 console.log(this.data.attributes) } }, }
模板部分修改
<template> <div> <!-- 异步请求完成前不渲染,避免undefined报错 --> <template v-if="data.attributes.length"> <!-- 循环渲染多条交易 --> <div v-for="transaction in data.attributes" :key="transaction.id"> <p>{{transaction.transaction_type}}</p> <div v-if="transaction.transaction_type !== 'sales'"> <p>Salesss</p> </div> </div> </template> </div> </template>
4. 可选校验步骤
如果修改后仍有问题,打开浏览器控制台检查接口响应的res.data结构,若后端返回的是嵌套结构(如{code:200, data: [...]}),赋值逻辑需对应调整为this.data.attributes = res.data.data。
内容的提问来源于stack exchange,提问作者Selaminko Elam
相关产品推荐
相关产品推荐

