Laravel Blade变量在JavaScript文件中引用报错的解决方案
Blade变量在Vite编译JS中未定义的解决方案
我在index.blade.php文件中定义了变量const deleteUrl = "{{ url('ingredients') }}/";,尝试在index.js中使用时,控制台报错:
Uncaught (in promise) ReferenceError: deleteUrl is not defined at index-4b1b8432.js:77:27775
相关代码片段
index.blade.php
<x-app-layout> {{-- 其他代码 --}} </x-app-layout> <x-slot name="jsFiles"> const deleteUrl = "{{ url('ingredients') }}/"; <script src="{{ asset("js/ingredients/index.js") }}"></script> </x-slot>
index.js
import $ from 'jquery'; $(function() { console.log(deleteUrl); });
app.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"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link rel="preconnect" href="https://fonts.bunny.net"> <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" /> <!-- Scripts --> @vite(['resources/css/app.css', 'resources/js/app.js', 'resources/js/ingredients/index.js']) </head> <body class="font-sans antialiased"> <div class="min-h-screen bg-gray-100"> @include('layouts.navigation') <!-- Page Heading --> @if (isset($header)) <header class="bg-white shadow"> <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8"> {{ $header }} </div> </header> @endif <!-- Page Content --> <main> {{ $slot }} </main> </div> <!-- JS Files --> {{ $jsFiles ?? '' }} </body> </html>
验证有效的解决方案
方案1:通过隐藏输入框传递变量
在Blade模板中添加隐藏输入框存储URL值:
<input type="hidden" id="deleteUrl" value="{{url('ingredients')}}/"/>
在index.js中读取该值:
import $ from 'jquery'; $(function() { const deleteUrl = $('#deleteUrl').val(); console.log(deleteUrl); });
方案2:在Vite加载前定义全局变量
修改app.blade.php,在@vite指令前插入脚本定义全局变量,确保Vite编译的JS加载时变量已存在:
<!-- Scripts --> <script> const deleteUrl = "{{ url('ingredients') }}/"; </script> @vite(['resources/css/app.css', 'resources/js/app.js', 'resources/js/ingredients/index.js'])
内容的提问来源于stack exchange,提问作者janullo789
相关产品推荐
相关产品推荐

