首页 > 解决方案 > 从 Laravel(在 api 文件夹中)获取数据到 Vue(放在另一个文件夹中)

问题描述

我在 api 文件夹中有 Laravel,而 Vue 在根文件夹中,我尝试将数据从 Laravel 传递到 Vue 组件。据我发现,我必须为此使用 axios,但我不知道如何。我现在正在寻找解决方案几个小时,但没有任何效果。PS。到目前为止,我没有在刀片中做任何事情。任何帮助,请!?

在此处输入图像描述

api/路由/api.php


Route::get('/content', 'ContentController@index');

内容控制器


    public function index() {
        $customers = Customer::all();
        return $customers;    
}

Vue 组件

<template>

</template>

<script>
import axios from 'axios'

export default {
  name: "Home"
};
</script>

标签: laravelvue.js

解决方案


由于您使用 Vue CLI 创建了 Vue 应用程序,运行 vue serve 会在本地 URL 启动您的应用程序,您需要让 Laravel API 应用程序也运行,以便您可以使用 Vue 组件中的 Axios 从它请求数据

cd api
php artisan serve

然后在你的模板中,你应该有这样的东西

<template>
    <div></div>
</template>

<script>
import axios from "axios";

export default {
    data() {
        return {
            databaseConfiguration: "",
            errors: {}
        };
    },
    name: "Home",
    created: function() {
        axios
            .get("http://127.0.0.1:8000/api/content")
            .then(response => {
                this.databaseConfiguration = response.data;
                console.log(response.data);
            })
            .catch(error => {
                this.errors.push(error);
                console.log(error);
            });
    }
};
</script>

这是GitHub 上一个完整的工作示例应用程序
希望这会有所帮助


推荐阅读