在 Javascript 文件中使用 Laravel Blade 中的变量

问题描述 投票:0回答:1

我的

const deleteUrl = "{{ url('ingredients') }}/";
文件中有变量
index.blade.php
。 我想在
index.js
中使用它,但在控制台中我有:

未捕获(承诺中)ReferenceError:deleteUrl 未在index-4b1b8432.js:77:27775 处定义

我可以做什么来修复它?

我的代码:

index.blade.php

<x-app-layout>
{{-- another code --}}
</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>
javascript laravel laravel-blade
1个回答
0
投票

将变量附加到窗口对象,使其全局可访问。

index.blade.php

<x-app-layout>
{{-- another code --}}
</x-app-layout>
<x-slot name="jsFiles">
    <script>
        window.deleteUrl = "{{ url('ingredients') }}/";
    </script>
    <script src="{{ asset("js/ingredients/index.js") }}"></script>
</x-slot>

index.js

import $ from 'jquery';
$(function() {
    console.log(window.deleteUrl);
    // Your other JavaScript code here
});
© www.soinside.com 2019 - 2024. All rights reserved.