【问题标题】:Get data from Laravel(in api folder) to Vue (placed in another folder)从 Laravel(在 api 文件夹中)获取数据到 Vue(放在另一个文件夹中)
【发布时间】:2019-11-07 15:01:53
【问题描述】:

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

api/routes/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>

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:

    由于您使用 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>
    

    这是full working example app on GitHub
    希望这会有所帮助

    【讨论】:

    • 好的,我这样做了:export default { axios.get('localhost:8081/content').then(response => console.log(response.data)), name: "Home" };但这并不好
    • 对不起,我收到一个错误 ' , ' ,我想这是我放置它的地方有问题,所以我编辑了代码。 export default { name: "Home", created: function() { axios.get("/content").then(response => console.log(response.data)); } }; -> 错误是针对意外的控制台语句,在线“console.log(response.data);
    • 模块错误(来自 ./node_modules/eslint-loader/index.js):,我复制/粘贴您的代码。我认为这是来自 eslint-loader,我会做一些研究,我会回复你一个答案,谢谢!
    • 你可以忽略这一点,eslint 只是一个 linter 来确保你的代码格式正确
    • 它无法编译 /2 发现的错误,对于 console.log。我会为此寻找解决方案,然后我会回来。
    猜你喜欢
    • 2018-12-14
    • 2014-02-10
    • 2020-07-30
    • 2017-02-11
    • 2012-12-01
    • 1970-01-01
    • 2010-09-08
    • 2012-11-11
    • 2020-05-06
    相关资源
    最近更新 更多