猿问

如何使用 Laravel 后端和 Vue 前端从数据库中获取数据?

作为一个附带项目,我正在尝试自学一些基本的全栈开发。这是一个非常有趣的领域,我非常想提高我的技能。


我目前的任务只是通过后端从数据库中获取数据,然后在前端以表格的形式显示出来。我选择的后端是 Laravel,我将它与 Vue 和 Bootstrap-Vue 一起用于前端部分。


下面是我在 HomeController.php 文件中的代码,我从标准用户表中获取所有数据库条目。


<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use \App\User


class HomeController extends Controller

{

    /**

     * Create a new controller instance.

     *

     * @return void

     */

    public function __construct()

    {

        $this->middleware('auth');

    }


    /**

     * Show the application dashboard.

     *

     * @return \Illuminate\Contracts\Support\Renderable

     */

    public function index()

    {

        $users = User::all();

        return view('home', compact('users'));

    }

}

然后我将这些条目发送到 home.blade.php 视图,如下所示:


@extends('layouts.app')


@section('content')

    <my-component></my-component>

@endsection

在这里,我想将$users数据传递给我的 Vue 组件(适当地命名为 my-component)。


在里面my-component,我想在表格中显示姓名和电子邮件。我遇到了Bootstrap-Vue,我非常喜欢他们组件的外观,因此我想学习使用它,在这种情况下,我使用的是他们的表格组件(请参阅下面的实现)。


但是,我被困在这一点上,如何将 传递$users到 vue 并items: [ ... ]用我的数据库数据替换 ?


我意识到有很多在线教程处理这个问题(CRUD 教程),但是其中大部分都是“获取此代码并将其粘贴到此处”的形式。当我试图学习它并没有帮助我使用教程中的其他人的代码时,并且在此过程中不知道如何,何时,何地和什么。


在我愤怒的“如何使用谷歌搜索”中,我遇到了以下问题,用户遇到了类似的问题。我按照相关链接阅读了propsVue 文档,但是我仍然不知道如何去做。


因此,我向您寻求帮助/协助/指导/智慧。


编辑:我的大部分“谷歌搜索”都说我必须使用 AJAX 请求,因此由于我使用的是 Laravel,我知道 axios 是执行此操作的内置工具。


繁星淼淼
浏览 226回答 1
1回答

喵喵时光机

又快又脏您可以将 JSON 中的数据作为道具传递<my-component :users='{{json_encode($users)}}'></my-component>export default{&nbsp; &nbsp; props:['users']}API方式每当我看到 Vue 和 Laravel 时,我的想法就直接进入了 SPA(单页应用程序)。这是您的所有网络路由(/home、/users 等)仅显示一个视图的位置,即应用程序本身,然后应用程序将通过对服务器的 API 调用(/api/users、/api)获取所需的任何数据/帖子)在上述架构中,您的控制器中将有一个新方法(例如_users()),它返回所有用户的 JSON 数据,然后您的前端可以使用该数据。(您也可以使用它而不使整个事情成为 SPA)_users(){ // resolve this in your routes.php as /api/users&nbsp; &nbsp; $users=Users::all()&nbsp; &nbsp; return $users; // Laravel will automagically cast toArray and json_encode}export default{&nbsp; &nbsp; data(){&nbsp; &nbsp; &nbsp; &nbsp; return{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; users:[]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; methods:{&nbsp; &nbsp; &nbsp; &nbsp; getUsers(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; axios.get('/api/users')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(response=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.users=response.data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; },&nbsp; &nbsp; mounted(){&nbsp; &nbsp; &nbsp; &nbsp; this.getUsers()&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答