Vue表单在Laravel项目中无法显示,页面空白问题求助
问题排查与修复方案
核心错误点
- Vue 3组件注册方式错误:你在app.js中混用了Vue 2和Vue 3的语法,Vue 3不存在全局
Vue对象,必须通过createApp返回的实例注册组件,且注册操作要在mount之前执行。 - HTML语法错误:welcome.blade.php的head标签内有多余的
</style>闭合标签,破坏了页面结构,导致渲染异常。 - 变量拼写错误:ApiCalling.vue的
createProduct方法中,this.product.pric少写了字母e,应为this.product.price,该错误会触发点击按钮时的异常。 - Axios引用缺失:组件中使用了axios但未明确导入,需确保axios已全局挂载或在组件内导入。
修正后的代码
app.js
import './bootstrap'; import { createApp } from 'vue'; const app = createApp({}); // 注册组件必须在mount之前执行 import ExampleComponent from './components/ExampleComponent.vue'; app.component('example-component', ExampleComponent); // 正确注册ApiCalling组件 import ApiCalling from './components/ApiCalling.vue'; app.component('api-calling', ApiCalling); app.mount('#app');
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> <link rel="stylesheet" href="/css/app.css"> </head> <body> <div id="app"> <api-calling></api-calling> </div> <script src="/js/app.js"></script> </body> </html>
ApiCalling.vue
<template> <div class="api-calling container mt-5"> <h1>Create Product</h1> <div class="form-group"> <label>Name</label> <input v-model="product.name" type="text" class="form-control" placeholder="Name..."> </div> <div class="form-group"> <label>Price</label> <input v-model="product.price" type="text" class="form-control" placeholder="Price..."> </div> <button class="btn btn-primary" @click="createProduct">Create</button> </div> </template> <script> // 若bootstrap.js未全局挂载axios,需在此导入 import axios from 'axios'; export default { data() { return { product: { name: '', price: 0 } } }, methods: { async createProduct() { try { const response = await axios.post('/products', { name: this.product.name, price: this.product.price // 修正拼写错误 }) console.log(response.data.product) } catch (error) { console.log(error) } } } } </script>
最后操作步骤
修复代码后,重新编译前端资源:
npm run dev # 生产环境使用: npm run build
内容的提问来源于stack exchange,提问作者Nathan Cr
相关产品推荐
相关产品推荐

