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

如何在Laravel项目中安装配置Vue并生成默认组件文件?

解决Laravel新项目中缺少Vue示例组件的问题

嘿,我完全懂你的困惑——现在新版本的Laravel已经不再默认生成Vue的示例组件和components文件夹了,这应该是你看的教程版本比较旧导致的差异。别担心,咱们有几种简单的办法来搞定这个问题:

方法1:手动创建基础Vue组件结构

这是最直接的方式,适合想要自定义组件结构的情况:

  • 在resources/js目录下新建components文件夹
  • 在components里创建ExampleComponent.vue,可以用下面的基础代码填充:
    <template>
      <div class="p-4 bg-gray-50 rounded-lg">
        <h2 class="text-xl font-semibold">Hello from Vue Example Component!</h2>
        <p class="mt-2 text-gray-600">这是一个手动创建的Vue组件</p>
      </div>
    </template>
    
    <script setup>
    // 在这里编写组件的逻辑代码
    </script>
    
  • 打开resources/js/app.js,引入并注册这个组件:
    import { createApp } from 'vue';
    import ExampleComponent from './components/ExampleComponent.vue';
    
    const app = createApp({});
    app.component('example-component', ExampleComponent);
    app.mount('#app');
    

方法2:用Laravel UI快速生成完整Vue脚手架

如果你想要和旧教程一模一样的默认结构,可以用Laravel UI包来生成:

  • 首先安装Laravel UI:
    composer require laravel/ui
    
  • 生成Vue的基础脚手架:
    php artisan ui vue
    
  • 最后安装依赖并编译前端资源:
    npm install && npm run dev
    
    执行完这些步骤后,你就能在resources/js下看到components文件夹和ExampleComponent.vue了。

方法3:针对后续接入Inertia的预配置

既然你之后要接入Inertia,其实可以直接按Inertia的流程来搭建,它会自动整合好Laravel和Vue的环境:

  • 先安装Inertia的Laravel端依赖:
    composer require inertiajs/inertia-laravel
    
  • 安装前端的Inertia Vue3依赖:
    npm install @inertiajs/vue3
    
  • 在resources/views下创建根模板app.blade.php,内容如下:
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel + Inertia + Vue</title>
        @vite('resources/js/app.js')
        @inertiaHead
      </head>
      <body>
        @inertia
      </body>
    </html>
    
  • 修改resources/js/app.js来初始化Inertia:
    import { createApp, h } from 'vue';
    import { createInertiaApp } from '@inertiajs/vue3';
    
    createInertiaApp({
      resolve: name => require(`./Pages/${name}.vue`),
      setup({ el, App, props, plugin }) {
        return createApp({ render: () => h(App, props) })
          .use(plugin)
          .mount(el);
      },
    });
    
    之后你可以创建resources/js/Pages文件夹存放页面组件,components文件夹可以自己创建来放复用的子组件,完全符合你的后续开发需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:53:50