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

Laravel Blade模板中@push指令与@component结合使用时JavaScript代码不生效的问题排查及解决方法

Why isn't @push('scripts') working with @component in my Laravel Blade templates?

Let's break down the issue you're facing and fix it step by step.

Your Setup Recap

You have three Blade files working together:

  • all.blade.php: Uses @component to wrap content and @push('scripts') to add a SweetAlert popup script
  • content.blade.php: Acts as a middle layout, extending the master template and rendering the component's slot content
  • master.blade.php: The root layout that structures the HTML page

The Root Cause

The problem boils down to the order of template rendering and stack placement. Right now, your @stack('scripts') is placed inside the <head> tag of master.blade.php. Here's what happens when the page loads:

  1. The <head> section renders first, including the empty @stack('scripts') (since the @push code in your component hasn't been processed yet)
  2. Then the <body> renders, which triggers the component and its @push logic
  3. By this point, the @stack('scripts') has already been output, so the pushed SweetAlert script never gets added to it

The Fix

Move the @stack('scripts') to the end of the <body> tag in master.blade.php, right after the @yield('content') directive. This ensures all @push calls from your components are processed before the stack is rendered.

Here's your updated master.blade.php:

<!DOCTYPE html>
<html>
<head>
    ... <!-- Your existing head content (meta tags, styles, etc.) -->
</head>
<body>
    @yield('content')

    <!-- Stack now loads after all content/components are processed -->
    @stack('scripts')
</body>
</html>

Why This Works

Now the rendering flow is correct:

  1. The <head> loads your base assets first
  2. The <body> renders your component, which triggers the @push('scripts') and adds the SweetAlert code to the stack
  3. Finally, @stack('scripts') outputs all pushed scripts at the end of the body, ensuring the code runs properly

Quick Check

Don't forget to confirm you've loaded the SweetAlert library itself! If you haven't, add this CDN link to your <head> in master.blade.php:

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:02:27