Ifrit's avatar
Level 2

Getting a null when console.log(this.user)

I'm using vue with my laravel site and when I click on a button I get taken to another page, the issue I'm having is that I'm not getting my info from my props.

When I console.log(this.user) in my CreateProduct.vue page I get a null

Here is my code

My app.js

Vue.component('index', require('../js/admin/Index').default);
Vue.component('create-product', require('../js/admin/CreateProduct').default);

if(document.getElementById('app) ! == null){
  const app = new Vue({
    el: '#app,
    data(){
        return {
          user: null
        }
    },
    methods:{

    },
    mounted(){
      axios.get('/api/getUser').then(response => {
        this.user = response.data;
      });
    }
  })
}

My Index.vue

<template>
  <div>
    <button class="btn btn-sm btn-success" @click="createProduct">Create Product</button>
  </div>
</template>

<script>
  export default{
    props: [],
    data(){
      return {

      }
    },
    methods: {
      createProduct(){
        window.location = /admin/create/product';
      }
    }
  }
</script>

Then my create-product.blade.php

@extends('layouts.app')
@section('content')
  <div id="app">
    <create-product :user="user"/>
  </div>
@endsection

and my CreateProduct.vue

<template>
  <div>
    This is the create product page
  </div>
</template>

<script>
  export default{
    props: ['user'],
    data(){
      return {

      }
    },
    methods: {
      
    },
    mounted(){
      console.log(this.user);
    }
  }
</script>
0 likes
2 replies
tykus's avatar

At the point the CreateProduct component is mounted, the XHR request still has not responded, so user has the initial null value from the root Vue instance.

I honestly don't understand what you are trying to achieve here, this is effectively a link that you are implementing in Vue????

MarianoMoreyra's avatar

Hi @ifrit

If what you are trying to achieve is to pass the authenticated User from Laravel to Vue, you should do something like this:

@extends('layouts.app')
@section('content')
  <div id="app">
    <create-product :user="{{ $user }}"/>
  </div>
@endsection

Of course, this assuming you are passing the $user from the Controller.

Also, be really careful about this, as you might be exposing User data that you may not want to expose!

Hope this helps

Please or to participate in this conversation.