首页 > 解决方案 > 将两个或多个变量从 laravel 控制器发送到 vue 组件

问题描述

假设我有一个像这样的 Vue 组件

export default {
    created() {
        axios.get("a url").then(res => {
            console.log(res.data);
        });
    }
};

然后 axios 在 laravel 控制器中向这个函数发送请求

public function something()
{
    $data = Model::all();
    $comments = Comment::all();
    // here i want to send both $data and $comments to that view
    return response()->json();
}

我可以把它们都寄出去吗?这个组件和函数只是一个例子

标签: phplaravelvue.jsaxios

解决方案


在这里你可以创建一个关联数组并通过 json 发送。

public function something()

    {
        $data=Model::all();
        $comments=Comment::all()
        return response()->json([
         'data'=>$data,
         'comments'=>$comments
       ]) //here i want to send both $data and $comments to that view
    }

在 Vue 中你可以写这样的东西。

export default
{
    data(){
       return {
         comments:[]
       }
    },
    created()
        {

           axios.get("a url")
                .then(res=>{
                    this.comments = [...res.data.comments] //If you are using ES6
                    }
        }
}

推荐阅读