Laravel包中使用Livewire 3的@script/@assets指令报错求助
问题描述
我正在开发一个Laravel包,用于提取日常使用的Blade组件供其他项目复用。我的Blade组件视图中包含Livewire的@script/@endscript以及@assets/@endassets指令,代码示例如下:
@assets <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script> <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.polyfills.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" /> @endassets @script <script> console.log('inside edit user script'); let input = document.querySelector('input[name=skills]'); // initialize Tagify on the above input node reference let tagify = new Tagify(input); </script> @endscript
该Blade组件已在包的ServiceProvider的boot()方法中通过以下代码注册:
Blade::component('tagify', TagifyComponent::class);
但从Laravel包内注册后,这些@script和@assets指令抛出错误:
Using $this when not in object context
解决方案
1. 修正组件类的继承关系
如果你的TagifyComponent是Livewire组件,必须继承Livewire\Component,而非普通的Blade组件类:
namespace YourPackageNamespace; use Livewire\Component; class TagifyComponent extends Component { // 组件业务逻辑 public function render() { return view('your-package::tagify'); } }
2. 使用Livewire专属的组件注册方式
不要用普通Blade组件的注册方法,改用Livewire的注册逻辑,在包的ServiceProvider的boot()方法中调整代码:
use Livewire\Livewire; use YourPackageNamespace\TagifyComponent; public function boot() { // 加载包的视图目录,指定命名空间 $this->loadViewsFrom(__DIR__.'/../resources/views', 'your-package'); // 注册Livewire组件 Livewire::component('tagify', TagifyComponent::class); }
3. 确保视图引用的命名空间正确
在组件的render()方法中,必须使用包的视图命名空间(如your-package::tagify)来引用视图文件,避免因视图加载上下文错误导致指令异常。
4. 确认组件的渲染上下文
@script和@assets是Livewire专属指令,只能在Livewire组件的视图中使用,不能在普通Blade组件或非Livewire模板中调用。如果是在普通Blade模板中使用,需要将组件改成Livewire组件后再调用。
内容的提问来源于stack exchange,提问作者Raheel Dharolia
相关产品推荐
相关产品推荐

