简体   繁体   English

Vue.js和Laravel传递json数据

[英]Vue.js and Laravel passing json data

I have been working on building a simple table that gets its data from a mongodb database that is being queried for the json data and not the data needs to be passed to the vue component on the frontend but I am unable to understand how the json data is transferred from laravel to vue.我一直致力于构建一个简单的表,该表从正在查询 json 数据的 mongodb 数据库获取数据,而不是需要将数据传递给前端的 vue 组件,但我无法理解 json 数据从 laravel 转移到 vue. To understand the code here is what I have done so far:要理解这里的代码是我到目前为止所做的:

api.php route: api.php 路线:

Route::middleware('api')->group(function () {
Route::resource('/home', [ProductController::class,'home']);
});

web.php route: web.php 路线:

Route::get('/home', [PostController::class,'home']);

PostController Home method: PostController Home 方法:

public function home() {
    $posts = Post::paginate(4);

    return response()->json($posts);
}

Home component:主页组件:

 <template> <div> <table> <tr> <td>Id</td> <td>Title</td> <td>Status</td> </tr> <tr v-for="El in results" v-bind:key="El.id" > <td>{{El.id}}</td> <td>{{El.STATUS}}</td> </tr> </table> </div> </template> <script> export default{ data() { return { results: [] }; }, methods: { fetch() { axios.get('/api/home').then(response => this.results = response.data).catch(error => console.log(error)); } } } </script>
Home.blade.php 主页.blade.php

 @extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Data</div> <div class="card-body"> <home-component></home-component> </div> </div> </div> </div> </div> @endsection

All of this seems fine but when I run the code it just show the json and does not render any of the vue component.所有这些看起来都很好,但是当我运行代码时,它只显示 json 并且不呈现任何 vue 组件。 Any help is appreciated.任何帮助表示赞赏。

You are using the /home URL both as a data endpoint and an HTML endpoint.您正在使用/home URL 作为数据端点和 HTML 端点。 What you should do is design it something like this:你应该做的是像这样设计它:

Route: GET /api/home
Returns: JSON data
Code: `return response()->json(...);`

Route:: GET /home
Returns: HTML data with javascript that requests /api/home
Code: `return view('home');`

Both routes are ordinary http requests, but one only serves JSON data and the other one serves HTML data to be interpreted by your browser.两条路由都是普通的 http 请求,但一条只服务 JSON 数据,另一条服务 HTML 数据,由您的浏览器解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM