在我的 Laravel 项目中,我编写了一个自定义表单验证类。使用 npm run dev 编译后,我无法访问此类。
我的文件
小表单验证.js
class SmallFormValidator {
errMsgs = {
required: 'This field is required!',
string: 'Not valid string.',
...
我的app.js
require('./bootstrap');
require('./myvendor/small-form-validator');
编译后,我在公共(public)文件夹内新创建的 app.js 文件中发现了类 SmallFormValidator 的源代码。看来他编译是对的。
在我的 Blade 模板中,我使用混合助手加载了 app.js 文件。在 Blade 模板内的 Javscript 中,我无法创建 SmallFormValidation 的实例(var sfv = new SmallFormValidation())。
我认为问题的结果是
- 我不处理模块导出等
- 或者我有一些范围问题。
有谁知道如何解决这个问题吗?
最佳答案
一个简单的解决方法是将其分配给您的全局/窗口对象。在 small-form-validation.js
中添加 window.SmallFormValidator = SmallFormValidator
以使其全局可访问。
更好的方法是使用模块导出和导入
示例
//add this add the end of the file
export default SmallFormValidator
// or to the line where you start declaring the class like so:
export default class SmallFormValidator {
// class stuff
}
在您想要使用它的文件中,您可以像这样导入它:
// top of your file
import SmallFormValidator from '../path/to/small-form-validation'
// use it how ever you want in this file
const smallFormValidator = new SmallFormValidator()
smallFormValidator.jeKaleZus() // or any other method you have
希望这有帮助
关于javascript - Laravel Mix 我无法访问我的 javascript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65846998/