Pass data from Blade template to Vue component

This is a new-comer question. I have a Blade template:

<div id="app">
    <example-component
    :componentMessage="appMessage"
    ></example-component>
</div>

<script>
    var app = new Vue({
        el: "#app",
        data: function() {
            return {
                appMessage: {{$message}}
            }
        }
    })
</script>

And a Vue component

resources/js/components/ExampleComponent.vue

<template>
    <p>{{componentMessage}}</p>
</template>

<script>
    export default {
        props: ['componentMessage'],
    }
</script>

So the data flow will look like this: $message -> appMessage -> componentMessage

The <example-component> is not working because I haven’t imported it properly.

How am I supposed to use Example component inside Blade template? Providing that I’m using Vue CDN and I want to keep the app declaration right on the Blade template for fancy data transformation (with Blade syntaxes) before passing it to component with appMessage in the middle?

I have been searching for documents. Some requires app declaration in resources/js/app.js, but if I follow this way, I can not pass data to app with Blade mustache syntax.

Update:

resources/js/app.js

import ExampleComponent from "./components/ExampleComponent.vue";

I have tried adding
<script src="{{mix('js/app.js')}}"></script>

And added components declaration in the instance:
components: {
    'example-component': ExampleComponent,
}

But it is still not working (Invalid Component definition: ExampleComponent). Probably I missed some steps.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Silly me. I do not need to declare components property in the app Vue instance. Just specify the component that you are going to use in resources/js/app.js and that component will be available globally in Blade template.

Watch for syntax differences between Laravel Mix differences tho. It could be the problem (Vue template or render function not defined yet I am using neither?)

import ExampleComponent from './components/ExampleComponent.vue';

Vue.component('example-component', ExampleComponent);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x