Laravel Mix 未定义 JavaScript 函数 [英] JavaScript function is not defined with Laravel Mix

查看:49
本文介绍了Laravel Mix 未定义 JavaScript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先在resources/js/app.js中编写代码

First , code in resources/js/app.js

function button1Clicked(){
  console.log('Button 1 is clicked');
}

二、test.blade.php中的代码

Second , code in testing.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Testing</title>
</head>
<body>
  <button onclick="button1Clicked()">Button 1</button>
  <button onclick="button2Clicked()">Button 2</button>

  <script type="text/javascript" src="{!! asset('js/app.js') !!}"></script>
  <script type="text/javascript">
    function button2Clicked(){
      console.log('Button 2 is clicked');
    }
  </script>
</body>
</html>

npm run dev 并在 localhost 中测试后

After npm run dev and testing in localhost

因此,resources/js/app.js 中的 JavaScript 函数 button1Clicked() 未定义.但是可以定义testing.blade.php中的button2Clicked()函数.是 Laravel Mix 的错误还是我犯了一些错误

As a result, JavaScript function button1Clicked() in resources/js/app.js is not defined. but the function button2Clicked() in testing.blade.php can be defined. Is it a bug from Laravel Mix or I did some mistakes

推荐答案

我遇到了和你一样的问题.

I had the same problem as you.

事实证明,当 Laravel-mix(又名 Webpack)编译 js 时,它会将我们的函数包装在一个闭包中.

It turned out that when Laravel-mix, aka Webpack, compile the js, it wraps our function in a closure.

例如,当我们定义一个这样的函数时

For example, when we define a function like this

function setlocale(code) {
     console.log(code);
}

Webpack 会生成成

Webpack will generate into

(function(module, exports, __webpack_require__) {

     function setlocale(code) {
         console.log(code);
     }

});

这就是为什么我们可以访问该闭包内部的变量或函数,但不能从外部访问,因为它限制了我们的范围.

That's why we can access the variables or functions inside that closure, but we cannot from the outside as it limits our scope.

一个简单的解决方案是将我们的函数设置为 window 变量,这是一个全局变量.

A simple solution is setting our function into window variable, which is a global variable.

window.setlocale = function (code) {
    console.log(code);
}

这篇关于Laravel Mix 未定义 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆