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

将Livewire组件转为Laravel常规组件时遭遇unexpected token "<"语法错误的技术问询

解决Laravel Blade组件调用的syntax error, unexpected token "<"问题

看起来你遇到的核心问题是从Livewire组件迁移到Laravel Blade组件时,没有遵循Blade组件的调用规则和类定义规范,导致了语法解析错误——即使组件内容为空,调用方式的错误依然会触发这个问题,下面是具体的排查和解决步骤:

1. 修正Blade组件的调用语法

你的组件调用代码里存在两个关键错误,这是导致unexpected token "<"的直接原因:

  • 传递PHP变量时,错误地使用了{{ }}包裹变量
  • 驼峰命名的参数没有转换为短横线命名格式

错误的调用:

<x-products.product-edit-modal :model="{{ $model }}" :currentSupplierId="{{ $model->custom_props_location_supplier->first()->supplier->id ?? null }}" :categories="{{ $categories }}" />

正确的调用:

<x-products.product-edit-modal 
    :model="$model" 
    :current-supplier-id="$model->custom_props_location_supplier->first()->supplier->id ?? null" 
    :categories="$categories" 
/>

关键说明:

  • :model="$model":使用:xxx绑定PHP变量时,直接写变量名即可,不需要{{ }}——{{ }}会把变量的内容输出为HTML文本,这会破坏组件标签的结构,导致解析器遇到意外的<符号(比如$model对象输出时会包含HTML或未转义的字符)
  • :current-supplier-id="...":Blade组件的参数如果是驼峰命名(比如类里的$currentSupplierId),在调用时必须转换为短横线分隔的命名,Laravel会自动将其映射为类中的驼峰属性

2. 确保Blade组件类的定义正确

你提到新组件是原Livewire组件的完整复制,这意味着你的组件类可能还是继承自Livewire的基类,而不是Laravel Blade组件的基类,必须修改组件类:

原Livewire组件类(错误):

namespace App\Http\Livewire;

use Livewire\Component;

class ProductEditModal extends Component
{
    // Livewire相关的属性和方法
}

修改后的Blade组件类(正确):

namespace App\View\Components\Products;

use Illuminate\View\Component;
use App\Models\Product; // 根据你的实际模型命名空间调整

class ProductEditModal extends Component
{
    public $model;
    public $currentSupplierId;
    public $categories;

    // 构造方法接收传递的参数,参数名要和调用时的短横线命名对应(自动转换为驼峰)
    public function __construct(Product $model, $currentSupplierId = null, $categories)
    {
        $this->model = $model;
        $this->currentSupplierId = $currentSupplierId;
        $this->categories = $categories;
    }

    // 返回组件视图
    public function render()
    {
        return view('components.products.product-edit-modal');
    }
}

注意事项:

  • 组件类要放在app/View/Components/Products目录下(对应调用时的x-products.product-edit-modal),Laravel 8+支持自动发现,不需要手动注册
  • 如果你的Laravel版本较低,需要在AppServiceProvider的boot方法里注册组件:
    use App\View\Components\Products\ProductEditModal;
    
    public function boot()
    {
        $this->components->register('products.product-edit-modal', ProductEditModal::class);
    }
    

3. 清理视图缓存

完成上述修改后,一定要清理视图缓存,避免旧的缓存文件导致错误:

php artisan view:clear
php artisan cache:clear

4. 排除Mix相关的干扰

虽然你怀疑Mix的问题,但由于注释组件内部代码后依然报错,Mix导致问题的可能性极低。不过可以重新编译资源确保没有残留问题:

npm run dev

总结

这个错误的核心是Blade组件的调用语法和类定义与Livewire完全不同,你需要完全按照Laravel Blade组件的规则来调整代码,重点修正变量传递的方式和组件类的继承关系,清理缓存后问题应该就能解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:12:44