如何在Vue组件中使用Laravel数据

时间:2018-12-14 07:32:40

标签: laravel vue.js components

文件结构

内部App.blade.php

我用vue路由器拉动组件。

我有一个普通变量,如$users,可以在刀片文件中访问,如{{$users}}。现在如何在组件中访问相同的数据?

3 个答案:

答案 0 :(得分:1)

如果您的$users变量是一个集合,则可以使用:

<my-component :users="{!! $users->toJson() !!}"></my-component>

答案 1 :(得分:0)

Laravel是php服务器端脚本语言,它在前端Javascript之前编译,而Vue是javascript。

因此要在js中获取php变量的值,请在输入文本字段中将此值作为json

<input type="hidden" id="users" value="{{json_encode($users)}}">

mount()内部的vuejs中,更新您的data'susers元素

mounted(){
   var users = document.querySelector("#users").value;
   users = JSON.pars(users);
   this.users = users;
}

答案 2 :(得分:0)

为此,我正在使用道具,看看我的例子:

我有一个QuestionComponent,我想向该文件发送有价值的$ quetion_set-> id,以便在刀片文件中我发送了一个道具,

public void onMessageReceived(RemoteMessage remoteMessage) {
        //handle when receive notification via data event
        if (remoteMessage.getData().size()>0){
            showNotification(remoteMessage.getData().get("body"));
        }
        //handle when receive notification
        if(remoteMessage.getNotification()!=null){
            showNotification(remoteMessage.getData().get("body"));
        }
    }

    private RemoteViews getCustomDesign(String title,String message) {

        RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(), R.layout.notification);
        remoteViews.setTextViewText(R.id.title,title);
        remoteViews.setTextViewText(R.id.message,message);
        remoteViews.setImageViewResource(R.id.icon,R.mipmap.ic_launcher_round);
        return remoteViews;

    }

    public void showNotification(String messageBody){

 try {
        JSONObject jsonBody = new JSONObject(messageBody);
        String link = jsonBody.getJSONObject("data").getString("link");
        Intent intent = new Intent(this, MainActivity.class);
        String channel_id = "web_app_channel";
        intent.putExtra("link", link);  // add this line for send url
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),channel_id)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setSound(uri)
                .setAutoCancel(true)
                .setVibrate(new long[] {1000, 1000, 1000, 1000, 1000})
                .setOnlyAlertOnce(true)
                .setContentIntent(pendingIntent);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

在QuestionComponent中,我设置道具: <question question_set_id="{{$question_set->id}}"/> ,然后在组件中使用它:props:['question_set_id'],

如果要传递数组数据,则应使用JSON.parse函数访问数据,例如:

this.question_set_id