laravelvue.jsvuejs3laravel-blade

Laravel how to implement Vue on a single blade page


I want to implement Vues on a single page of my Laravel application. I was able to do it via CDN but need to do it via npm

This is my blade page:

<div class="app">
        @{{state }}
    </div>
    
    <script type="module">

        import { createApp } from '/vue';

        createApp({
            data() {
                return {
                    state: true,
                };
            },
            mounted() {
                console.log("life works");
                console.log(window.Echo); // Check if Echo is available
                window.Echo.channel('chats')
                    .listen('TestRevertWorks', (e) => {
                        console.log(e.message);
                    });
            }
        }).mount('#app');

my console has following error:

GET http://localhost:3001/vue 404 (Not Found)

This is how I installed and implement vue.

npm install vue @vitejs/plugin-vue
npm install vue@latest  

Then in my app.js:

import './bootstrap';

import { createApp } from 'vue'

const app = createApp()

app.mount('#app')

Then in vite.config.js

import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
import vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/js/apps.js',
               
            ],
            refresh: true,
        }),
        vue(),
        react(),
    ],
    resolve: {
        alias: {
            '$': 'jQuery',
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    },
});

Then on header of blade page:

@vite(['resources/js/app.js'])

Solution

  • In your app.js

    const app = createApp({});
    
    // Register a component that you're trying to use. So if you have multiple components then you can register it using app.component().
    app.component('example-component', ExampleComponent);
    app.mount('#app');
    

    In your blade page, considering you already have app.js imported, you can use registered components. You can also pass the props. $message is the Laravel variable here.

    <div id="app">
        <!-- OTHER BLADE TEMPLATE HERE -->    
        <example-component :message={{ $message }}></example-component>
    </div>