在Vue组件中解析JSON编码的数据

时间:2019-05-03 09:05:42

标签: laravel vue.js

我正在将json encoded数据作为Vue component传递给我的prop,当我打印整个prop变量时,这表明数据已成功接收,但是我正在无法解析数据。

profile.blade.php

@extends('layouts.app')

@section('content')

    <my-profile user-details="{{ json_encode($userDetails) }}"></my-profile>

@endsection

MyProfile.vue

<template>
    <div class="container">
        <div class="row justify-content">
            <div class="col-md-3" id="profile-image">
                <img class="img-fluid rounded" src="https://www.w3schools.com/bootstrap4/paris.jpg" alt="Profile Image">
            </div>            
            <div class="col-md-12">
                <p>{{userDetails}}</p>
                <p> Name:  {{ userDetails.first_name }} </p>
            </div>
        </div>
    </div>
</template>

<style>
#profile-image {
margin-bottom: 30px;
}
</style>

<script>
export default {
props: ["userDetails"]
}
</script>

输出

    {"user_id":2,"first_name":"Shan","last_name":"Biswas","email":"shanpro.2015@gmail.com","phone":"9508168983","created_at":"2019-05-03 05:43:17","updated_at":"2019-05-03 05:43:17"}

    Name:

3 个答案:

答案 0 :(得分:0)

更改此:

<my-profile user-details="{{ json_encode($userDetails) }}"></my-profile>

与此:

<my-profile user-details='@json($userDetails)'></my-profile>
// Pay attention to single quotes instead of double

这对我有用。

答案 1 :(得分:0)

将profile.blade.php更新为以下内容!

@extends('layouts.app')

@section('content')

    <my-profile user-details="{{ $userDetails }}"></my-profile>

@endsection

答案 2 :(得分:0)

您需要将该值绑定为动态的而不是静态的组件。 因此,将您的刀片文件更改为:

@extends('layouts.app')

@section('content')
    <!-- see the colon in front of the props, that is a shortcut for v-bind:prop-name -->
    <my-profile :user-details="{{ json_encode($userDetails) }}"></my-profile>

@endsection

否则,所有值都作为简单字符串传递给组件。