简体   繁体   English

如何在 Laravel Blade 中使用单独的 js 文件

[英]How to use seperate js files in Laravel Blade

I'm trying to have different JS files for each Blade View in Laravel to help keep the project structure clean.我正在尝试为 Laravel 中的每个 Blade View 使用不同的 JS 文件,以帮助保持项目结构的整洁。

My problem is, when I try to access a function from that JS file in a Blade view, the console returns an error of:我的问题是,当我尝试在 Blade 视图中从该 JS 文件访问 function 时,控制台返回错误:

Uncaught ReferenceError: myFunc is not defined at HTMLButtonElement.onclick未捕获的 ReferenceError:myFunc 未在 HTMLButtonElement.onclick 中定义

But the file is there and it logs the console message from that js file.但是文件在那里,它记录了来自该 js 文件的控制台消息。

Here are my files and structure:这是我的文件和结构:

resources/js/index.js资源/js/index.js

console.log("Hello from index js");

function myFunc() {
    console.log("Hello");
}

resources/views/layout/master.blade.php资源/视图/布局/master.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
    </head>
    <body>
       @yield('content')
       {{-- @yield('js') --}}
       @stack('js')
    </body>
</html>

resources/views/index.blade.php资源/视图/index.blade.php

@extends('layout.master')
@section('content')
    <h1>Works</h1>
    <button onclick="myFunc()">Click</button>
@endsection
@push('js')
<script src="{{ asset('js/index.js')}}"></script>
@endpush

webpackmix.mix.js webpackmix.mix.js

const mix = require("laravel-mix");

mix.js("resources/js/app.js", "public/js").postCss(
    "resources/css/app.css",
    "public/css",
    [
        //
    ]
);

mix.js("resources/js/index.js", "public/js");

Your function defined in script that loaded after main body content, but you trying to access this function in main body content.您的 function 在主体内容后加载的脚本中定义,但您试图在主体内容中访问此 function。

  • Try to switch to selector for the button in JS file尝试切换到JS文件中按钮的选择器
  • Or load script sync before body (BAD: defers content render)或者在正文之前加载脚本同步(坏:延迟内容渲染)

@murrayOB you can just create your separate js file in public and then js folder and just include it in your default.blade.php file like that <script src="{{asset('js/common-flow.js')}}"></script> and after that just call any function from blade file written in that specific common-flow file @murrayOB 你可以在 public 中创建单独的 js 文件,然后在 js 文件夹中创建它,然后将它包含在你的 default.blade.php 文件中<script src="{{asset('js/common-flow.js')}}"></script>之后,只需从写入该特定通用流文件的刀片文件中调用任何 function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM