You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel项目中正确配置VueRouter?解决组件未注册报错

解决Laravel中VueRouter的"Unknown custom element: "错误

这个报错的核心原因非常直接:你把VueRouter用来渲染匹配路由组件的容器标签写错了!正确的标签是<router-view>,而不是你写的<router-vue>,Vue找不到这个自定义组件所以抛出了警告。

下面是完整的修正步骤和优化后的代码:

1. 修正App.vue中的路由视图标签

把<router-vue>替换为<router-view>,同时给<router-link>加上显示文本(不然用户看不到可点击的链接):

<template>
  <div>
    <div>
      <!-- 添加链接文本,方便用户识别点击 -->
      <router-link :to="/">首页</router-link>
      <router-link :to="/example">示例页面</router-link>
    </div>
    <div>
      <!-- 正确的路由视图容器 -->
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default { }
</script>

2. 优化app.js的配置(可选,但更规范)

你的app.js基础配置是对的,不过可以做一点小优化,比如用render函数替代template和组件注册,同时可以明确路由模式:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './components/App'
import ExampleComponent from './components/ExampleComponent'
import ExampleComponent1 from './components/ExampleComponent1'

Vue.use(VueRouter)

const router = new VueRouter({
  // 默认是hash模式(URL带#),如果想去掉#可以用history模式,需要配合Laravel路由配置
  mode: 'hash',
  routes: [
    { path: '/', component: ExampleComponent },
    { path: '/example', component: ExampleComponent1 }
  ]
})

const app = new Vue({
  el: '#app',
  router,
  // 推荐用render函数,比template写法更简洁高效
  render: h => h(App)
})

3. 可选:启用history模式(去掉URL中的#)

如果不想URL里带#,可以把路由模式改成history,但需要在Laravel的routes/web.php中添加一个 fallback路由,让所有前端路由都指向Vue的入口视图:

Route::get('/{any}', function () {
    // 这里替换成你的Vue入口视图,比如默认的welcome.blade.php
    return view('welcome');
})->where('any', '.*');

同时在VueRouter的配置里修改:

const router = new VueRouter({
  mode: 'history', // 启用history模式
  routes: [/* ... */]
})

做完这些修改后,重新编译你的前端资源(npm run dev或npm run watch),刷新页面就能正常使用VueRouter了。

内容的提问来源于stack exchange,提问作者Andrey Fugas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:28:31