如何在Laravel 9 Blade中渲染Vue 3的router-view?
在Laravel Blade中渲染Vue Router组件的解决方案
问题核心原因
你当前的代码逻辑存在冲突:app.js 是将 App.vue 作为根组件挂载到 #app 元素上,而Vue在挂载时会完全替换#app内部的所有内容。这意味着你在welcome.blade.php的#app里写的<router-link>和<router-view>会被App.vue的模板覆盖,导致页面无内容显示。
解决方案步骤
1. 调整根组件(App.vue)的结构
修改App.vue,让它仅作为插槽容器,保留Blade模板里的内容:
<template> <slot></slot> </template> <script setup> // 这里可以保留全局需要的逻辑,比如导入全局样式、全局方法等 </script>
2. 确保路由配置正确且全局组件可用
检查你的路由配置,确保路由组件正确导入并注册:
// app.js import './bootstrap'; import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import axios from 'axios'; // 导入你的路由组件(根据实际路径调整) import Home from './components/Home.vue'; import About from './components/About.vue'; // 定义路由规则 const routes = [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About }, ]; // 创建路由实例 const router = createRouter({ history: createWebHistory(), routes, }); // 创建Vue实例并挂载 const app = createApp({ template: '<slot></slot>' }); // 全局注册axios app.config.globalProperties.$axios = axios; // 注册路由,Vue Router会自动全局注册<router-link>和<router-view> app.use(router); // 如果需要在Blade里使用自定义组件(比如原来的NavMenu),要全局注册 // import NavMenu from './components/NavMenu.vue'; // app.component('NavMenu', NavMenu); app.mount('#app');
3. 修复Blade模板中的标签错误
welcome.blade.php里的<router-link>标签未闭合且无文本内容,修改为:
<!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <title>{{ env('APP_NAME') }}</title> </head> <body> <div id="app"> <!-- 修复router-link标签,添加文本并闭合 --> <router-link :to="{ name: 'home' }">首页</router-link> <router-link :to="{ name: 'about' }">关于</router-link> <router-view></router-view> </div> @vite('/resources/js/app.js') </body> </html>
4. 验证路由组件存在
确保Home.vue和About.vue等路由组件存在于指定路径下,比如resources/js/components/目录,示例如下:
<!-- Home.vue 示例 --> <template> <div> <h1>首页</h1> <p>这是首页内容</p> </div> </template>
测试运行
执行以下命令重新编译资源并启动服务:
npm run dev php artisan serve
访问应用后,应该能看到导航链接和对应路由的内容正常渲染。
内容的提问来源于stack exchange,提问作者IT Time Programming
相关产品推荐
相关产品推荐

