2
votes

I try to pass data from Laravel blade to Vue with props and I get undefined in console. I tried also

<example-component :course="{{ $course }}"></example-component>
<example-component course="{{!! $course !!}}"></example-component>

index.blade.php

@extends('layouts.app')

@section('content')
    <div id="app">
    
    </div>
    
    <example-component course="{{ $course }}"></example-component>

    <script src="{{asset('js/course/app.js')}}"></script>
@endsection

app.js

import { createApp } from 'vue';
import App from './components/App.vue'
import router from '../../router'
createApp(App).use(router).mount("#app")

App.vue

<template>
{{ course }}
</template>

<script>
export default {
props: ['course'],
mounted() {
console.log(this.course)
}
}
</script>
2
what seems to be the issueHassaan Ali
I get undefined in console and the question is why?xMrViktorx
Well it depends on where you're including your js. If it's included in head then it'll show undefined because the DOM is not loaded yet and if the script is set to DOMContentLoaded then it'll first wait for DOM to load then it'll not show any error in console. Have you tried something like that?Hassaan Ali

2 Answers

0
votes

The best practice is to make you component call an API to get the course.

If it's not worth an API try to pass the $course as attr to your #app element. Then you can get your course with getAttribute

<div id="app" course="{{json_encode($course)}}"></div>

in vue.js:

document.getElementById('app').getAttribute('course')
0
votes

You've to create a component named ExampleComponent and registered globally :

<template>
{{ course }}
</template>

<script>
export default {
props: ['course'],
mounted() {
console.log(this.course)
}
}
</script>

And App.vue

<template>
<div>App</div>
</template>

<script>
export default {

}
</script>

app.js

import { createApp } from 'vue';
import App from './components/App.vue'
import ExampleComponent from './components/ExampleComponent.vue'
import router from '../../router'
let app=createApp(App)
app.component('example-component',ExampleComponent)
app.use(router).mount("#app")

Your component should be inside the div with app as id where the vue app is mounted :

@extends('layouts.app')

@section('content')
    <div id="app">
       <example-component course="{{ $course }}"></example-component>
    </div>
    
    

    <script src="{{asset('js/course/app.js')}}"></script>
@endsection