【问题标题】:Json response returns nested objectJson 响应返回嵌套对象
【发布时间】:2020-11-17 07:10:05
【问题描述】:

我是 vue laravel 的新手,正在尝试使用 json 响应从 API 控制器获取数据。我觉得在嵌套对象中获取数据并不是最佳实践。实现这一点的最佳方法是什么,以便我可以得到this.user_data.designations = All_Designation(with res.data) 和其他一些像this.user_data.employment = All_Employments 等。

当我尝试通过 props 发送数据时,我可以访问它

designations:  this.data.map(d => ({label: d.designation_name, value: d.designation_name, id:d.id}))

我还想要其他数据,所以我想应该是 this.data.designations, this.data.employment。这让我很困惑。 我怎样才能在不改变特质的情况下管理所有事情

这是我的控制器方法:

public function index()
{
    $designations = Designation::all();
    if (!$designations->isEmpty()) {
        $this->responseData['response'] = 1;
        $this->responseData['message'] = "Designations has been Recieved.";
        $this->responseData['data'] = $designations;
        $this->status = 200;
    }
    return $this->apiResponse();
}

API 特征:

protected $responseData = [
    'response' => 0,
    'message' => "Not Found",
    'data' => null
];
/**
 * @var int
 */
protected $status = 404;
/**
 * @return mixed
 */
public function apiResponse()
{
    return response()->json($this->responseData, $this->status);
}

Axios 调用:

this.$store.dispatch('employee/getDesignations' )
    .then(res => { this.user_data.designations = res.data.data })
    .catch(err => {
      console.error(err) 
    })

【问题讨论】:

    标签: laravel vue.js response


    【解决方案1】:

    像这样返回响应

    return response()->json(['response' => ['status' => true, 'data' => $apiResponse]], JsonResponse::HTTP_OK);
    

    HTTP_OK =200 并且它的枚举类型为use Illuminate\Http\JsonResponse; status =true 表示您返回数据。

    例如,如果您的数据为空,则返回类似的内容

    return response()->json(['response' => ['status' => false, 'message' => 'Unable to find data ']], JsonResponse::HTTP_BAD_REQUEST);
    

    只返回这个。

    return response()->json($data, JsonResponse::HTTP_OK);
    

    希望对你有帮助

    【讨论】:

    • 感谢您的努力,但它变得更加嵌套。现在我通过 response.data.data 获取数据,我猜这不是一件好事
    • 返回响应()->json($data, JsonResponse::HTTP_OK);使用这个
    猜你喜欢
    • 2020-10-23
    • 2017-03-15
    • 1970-01-01
    • 2017-04-05
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2020-12-27
    相关资源
    最近更新 更多