Laravel 10+Vue新项目中ExampleComponent组件无法显示问题排查
问题描述
通过以下命令创建Laravel 10 + Vue 3新项目:
composer create-project laravel/laravel vue3 cd vue3 composer require laravel/ui php artisan ui vue --auth npm install npm run dev
启动本地服务器后,resources/views/welcome.blade.php内容正常显示。为测试Vue功能,在该文件中添加:
<div> <example-component></example-component> </div>
但页面无法显示该组件输出,开发者控制台无报错(修改文件其他内容可正常生效)。相关配置文件如下:
package.json
{ "private": true, "scripts": { "dev": "vite", "build": "vite build" }, "devDependencies": { "@popperjs/core": "^2.11.6", "@vitejs/plugin-vue": "^4.0.0", "axios": "^1.1.2", "bootstrap": "^5.2.3", "laravel-vite-plugin": "^0.7.2", "sass": "^1.56.1", "vite": "^4.0.0", "vue": "^3.2.37" } }
resources/js/app.js
import './bootstrap'; import { createApp } from 'vue'; const app = createApp({}); import ExampleComponent from './components/ExampleComponent.vue'; app.component('example-component', ExampleComponent); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // Object.entries(import.meta.glob('./**/*.vue', { eager: true })).forEach(([path, definition]) => { // app.component(path.split('/').pop().replace(/\.\w+$/, ''), definition.default); // }); /** * Finally, we will attach the application instance to a HTML element with * an "id" attribute of "app". This element is included with the "auth" * scaffolding. Otherwise, you will need to add an element yourself. */ app.mount('#app');
问题原因与修复方案
问题核心原因
Vue实例通过app.mount('#app')挂载到了ID为app的DOM元素上,但你添加的<example-component>不在这个元素内部,Vue无法识别并渲染该组件。另外需确保页面正确引入了Vite编译的Vue资源。
修复步骤
- 修改welcome.blade.php,添加Vue根容器
将你的Vue组件包裹在ID为app的元素内,并确保页面引入Vite资源。修改后的welcome.blade.php示例:
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel</title> <!-- 引入Vite编译的JS资源 --> @vite(['resources/js/app.js']) </head> <body> <!-- Vue根容器 --> <div id="app"> <div> <example-component></example-component> </div> </div> </body> </html>
- 确保资源编译正常
- 确认
npm run dev命令处于运行状态,Vite正在实时编译资源 - 硬刷新浏览器(Ctrl+F5)清除缓存,重新加载页面
- 可选:调整Vue挂载目标(不推荐)
如果不想使用#app作为根容器,可以修改app.js中的挂载代码,比如改为挂载到body(不推荐,可能引发全局冲突):
// 替换原有的app.mount('#app') app.mount('body');
但更合理的做法还是使用专门的根容器来隔离Vue应用。
内容的提问来源于stack exchange,提问作者user761100
相关产品推荐
相关产品推荐

