将laravel变量传递给Vue前端

时间:2019-10-14 12:54:54

标签: javascript php laravel vue.js

为了将php变量从laravel传递到vue前端,我创建了一个Javascript类,我使用此类的static put方法将关联数组发送到前端。

<?php
namespace App\Helpers;


class Javascript
{

    public static function put($array, $request)
    {
        //I call this static method to pass backend variables to Vue, from blade I json_encode the payload, assign it to a window variable
        //and later add it to the Vue.prototype so I can access in vue components like this.$app.whatever.

        //This helper method can be called more than one time in laravel's request->reponse cycle, from middleware, controller action, route redirect ... 
        //so instead of creating recreating $app array everytime I want to find a way to push passed key value pairs to a global javascript object

        $app = array();

        $app = array_merge($request->globals, $array);

        view()->share('app', $app);
    }

}

当我想返回带有JavaScript数据的laravel刀片视图时,我会这样做:

$featuredPosts = Post::where('isFeatured', true)->where('isVisible',true)->with('postcategory')->get();

Javascript::put([
  'meta' => $meta,
  'featuredPosts' => $featuredPosts,
], $request);

return view('publicaciones.list', compact('meta'));

在刀片主布局中:

<script type="text/javascript">window.$app = {!! json_encode( $app ) !!};</script>

另一种情况是当我想为所有路径/视图都具有全局变量时,为此,我在其中有一个名为GlobalsVar的全局中间件。

public function handle($request, Closure $next)
{
   $globals['auth'] = Auth::user() ?  User::with('appointment')->find(Auth::id()) : false;

   $globals['previousUrl'] = URL::previous();

   $request->globals = $globals;

   return $next($request);
}

当前,在我的Javascript类中,我创建了一个empy数组,并将部分请求与控制器传递的数组合并,我还将请求对象作为seconda参数传递,我想通过两种方式对此进行改进:

1)每次我调用Javascript :: put静态方法时,传递的值都会合并到现有对象中,这是因为如果在请求->响应周期中,我调用Javascript :: put会重新创建有效负载,并且先前的数据是丢失了,有没有办法保存这些数据?

2)我不想每次运行Javascript :: put时都传递Request $ request对象,有没有办法总是注入Request方法

1 个答案:

答案 0 :(得分:0)

如果您的刀片呼叫提示,则可以传递道具等Laravel数据

@extends('index')
@section('contenido')
  <div id="content-container">
     <div id="page-head">
     </div>
     <div id="page-content">
        <vue-file :variable="{{ $variable}}"></vue-file>
    </div>
@endsection

在vue文件中,您可以像这样

props:{
 variable:Array  
}