简体   繁体   中英

Vue component error in Laravel "Unknown custom element"

I'm trying to use Vue for the first time in laravel but have been struggling to get it working and keep running into the same error.

在此处输入图像描述

resources/js/app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

const app = new Vue({
    el: '#app'
})

resources/views/index.blade.php

@extends('header')
<title>{{ config('app.name') }}</title>
@section('content')

<div id='app'>
<example-component></example-component>
</div>

<script src="js/app.js"></script>
@endsection

resources/js/components/ExampleComponent.vue

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        <strong>I'm an example component.</strong>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name:'example-component',
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

Yes I have vue installed and have done npm install and npm run dev. for the record npm install refused to generate an app.js file inside public/js so I had to copy and paste one from a different project.

You are missing the point of using Vite or Laravel's assets in general...

I see you are expecting a js/app.js file and you literally have <script src="js/app.js"></script> . That is not have Laravel works. If you read this section of the documentation (prior to Vite), you had to use mix(...) to get the final URL of the asset, if you are using the new vesion (Vite), now you have to use @vite(...) ...

So you should run npm run build (or dev ) and then your code should be like this:

@extends('header')

<title>{{ config('app.name') }}</title>

@section('content')
<div id='app'>
    <example-component></example-component>
</div>

@vite('resources/js/app.js')
@endsection

Forget about expecting to have app.js on the public folder or anything similar, never do that with any framework, always the read the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM