【问题标题】:send two or more variable from laravel controller to vue component将两个或多个变量从 laravel 控制器发送到 vue 组件
【发布时间】:2020-01-07 01:14:57
【问题描述】:

假设我有一个像这样的 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();
}

我可以同时发送它们吗? 这个组件和函数只是一个例子

【问题讨论】:

    标签: php laravel vue.js axios


    【解决方案1】:

    在这里你可以创建一个关联数组并通过 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
                        }
            }
    }
    

    【讨论】:

      【解决方案2】:

      你可以通过使用 laravel 的response 方法来实现这一点

      public function something()
      {
          $data=Model::all();
          $comments=Comment::all()
          return response()->json([
               'data'=> $data,
               'comments'=> $comments
             ], 200);
      }
      

      或其他方式使用相同的方法

      public function something()
      {
              $data=Model::all();
              $comments=Comment::all()
              return response([
               'data'=> $data,
               'comments'=> $comments
              ], 200);
      }
      

      在您的组件中,您可以简单地使用获取数据

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

      谢谢

      【讨论】:

        【解决方案3】:

        你可以这样做

        public function function()
        
        {
            $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
        }
        

        【讨论】:

        • 请对您的回答提供一些解释
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        • 2021-10-13
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        • 2019-10-18
        • 2019-06-27
        相关资源
        最近更新 更多