首页 > 解决方案 > Laravel Mix Vue,使用Vue Router时延迟加载组件返回错误作为未知自定义元素

问题描述

我已经全新安装了 Laravel Mix,我正在尝试在项目中设置延迟加载组件。我已经使用 babel 插件 'syntax-dynamic-import' 进行了正确设置,因此 app.js 中的 import 语句按预期工作。当我尝试将延迟加载的组件与 vue-router 一起使用时,会出现此问题。

我的 app.js 文件如下所示:

require('./bootstrap');

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const EC = () => import(/* webpackChunkName: "example-component" */ './components/ExampleComponent.vue');

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/', component: EC }
    ]
});

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

我的welcome.blade.php 文件如下所示:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Laravel</title>

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <base href="/" />
</head>
<body>
<div id="app">
    <h1>Base title</h1>
    <example-component></example-component>
</div>

<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

所以我只是试图登陆根路由并显示示例组件。示例组件包含在 welcome.blade.php 文件中。

我在控制台中收到此错误:

[Vue warn]: Unknown custom element: <example-component> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in <Root>)

我想我错过了一些简单的东西,任何建议都值得赞赏。

标签: vue.jslazy-loadingvue-routerlaravel-mix

解决方案


首先,我认为您将路由概念与核心组件 vue 概念混合在一起......

尝试直接在您的 vue 应用程序中加载组件...

const app = new Vue({
    router,
    el: '#app',
    components: {
        'example-component': () => import('./components/ExampleComponent.vue')
    }
});

组件加载完成<component>

<component v-bind:is="currentTabComponent"></component>

查看文档,了解有关动态组件的更多信息:https ://vuejs.org/v2/guide/components-dynamic-async.html


推荐阅读