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

如何将Vue.js 3与Laravel 10项目对接并向Vue组件传值?

Laravel 10 对接 Vue.js 3 完整解决步骤

一、修复js/app.js找不到的报错

你参考的指南基于旧版Laravel的Mix构建工具,而Laravel 10默认使用Vite,这是报错核心原因,按以下步骤修正:

  • 确认项目根目录下存在resources/js/app.js,没有则手动创建:
    // 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')
    
  • 检查vite.config.js配置,确保入口文件包含app.js:
    // vite.config.js
    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    import vue from '@vitejs/plugin-vue';
    
    export default defineConfig({
        plugins: [
            laravel({
                input: ['resources/css/app.css', 'resources/js/app.js'],
                refresh: true,
            }),
            vue({
                template: {
                    transformAssetUrls: {
                        base: null,
                        includeAbsolute: false,
                    },
                },
            }),
        ],
    });
    
  • 安装依赖:
    npm install
    npm install @vitejs/plugin-vue vue@3
    
  • 启动开发服务器编译资源:
    npm run dev
    
  • 在Blade模板中用@vite指令引入资源,禁止手动写<script>标签:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Laravel Vue Demo</title>
        @vite(['resources/css/app.css', 'resources/js/app.js'])
    </head>
    <body>
        <div id="app">
            <example-component></example-component>
        </div>
    </body>
    </html>
    

二、无HTTP请求传递Laravel数据到Vue组件

通过组件Props实现数据传递:

  1. 在Vue组件中定义接收的Props:
<!-- resources/js/components/ExampleComponent.vue -->
<template>
  <div>
    <h2>从Laravel获取的数据:</h2>
    <p>用户名:{{ username }}</p>
    <p>用户ID:{{ userId }}</p>
  </div>
</template>

<script setup>
const props = defineProps({
  username: String,
  userId: Number
})
</script>
  1. 在Blade模板中传递数据:
<div id="app">
  <!-- 动态传递Laravel变量 -->
  <example-component 
    :username="{{ json_encode(Auth::user()->name) }}"
    :user-id="{{ Auth::user()->id }}"
  ></example-component>

  <!-- 静态数据传递示例 -->
  <example-component 
    username="张三"
    :user-id="123"
  ></example-component>
</div>

三、常见问题排查

  • 开发环境必须保持npm run dev运行,生产环境需执行npm run build编译静态资源。
  • 检查浏览器控制台的网络请求,确认资源路径是否正确,Vite开发模式下资源路径通常指向localhost:5173。
  • 确认.env文件中的APP_URL配置正确,Vite依赖该路径生成资源链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:18:46