【Laravel實戰】5分鐘搞懂Livewire的 Inline Scripts 撰寫
Livewire 建議你將 AlpineJS 用於大多數 JavaScript 需求,但它確實支持直接在你的組件視圖裡頭使用 <script> 標籤
<div>
<!-- 你的組件 HTML -->
<script>
document.addEventListener('livewire:load', function () {
// 在這裡撰寫你的 JS 程式碼.
})
</script>
</div>
請注意,您的腳本僅在首次渲染組件時運行一次。如果你以後需要運行 JavaScript 函數,請從該組件發出事件,然後按如下所述在 JavaScript 中偵聽該事件
你還可以從 Livewire 組件將腳本直接推送到 Blade 堆疊上:
@push('scripts')
<script>
// Your JS here.
</script>
@endpush
訪問 JavaScript 組件實例
由於 Livewire 同時具有 PHP 和 JavaScript 區塊,因此每個組件也都有一個 JavaScript 物件。你可以在組件視圖中使用特殊的 @this Blade 指令訪問此對象
這是一個例子:
<script>
document.addEventListener('livewire:load', function () {
// Get the value of the "count" property
var someValue = @this.count
// Set the value of the "count" property
@this.count = 5
// Call the increment component action
@this.increment()
// Run a callback when an event ("foo") is emitted from this component
@this.on('foo', () => {})
})
</script>
注意
@this 指令將編譯為以下字串以供 JavaScript 解析:"Livewire.find([component-id])""



