Santanu Biswas
Santanu Biswas

Reputation: 181

Parse JSON encoded data in Vue Component

I am passing a json encoded data to my Vue component as a prop, when I am printing the whole prop variable then it is showing that the data has successfully received, but I am not able to parse the data.

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>

Output

    {"user_id":2,"first_name":"Shan","last_name":"Biswas","email":"[email protected]","phone":"9508168983","created_at":"2019-05-03 05:43:17","updated_at":"2019-05-03 05:43:17"}

    Name:

Upvotes: 2

Views: 13517

Answers (3)

Silencesys
Silencesys

Reputation: 565

You need to bind the value to the component as dynamic and not static. So change your blade file to:

@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

Otherwise are all values passed to the component as a simple string.

Upvotes: 5

Akm
Akm

Reputation: 81

Update profile.blade.php to following!

@extends('layouts.app')

@section('content')

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

@endsection

Upvotes: 0

Cristian Cosenza
Cristian Cosenza

Reputation: 223

Change this:

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

with this:

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

This worked for me.

Upvotes: 1

Related Questions