在 JS 模块中使用 Rails-UJS(带有 webpacker 的 Rails 6) [英] Using Rails-UJS in JS modules (Rails 6 with webpacker)
问题描述
我刚刚切换到 Rails 6 (6.0.0.rc1),它默认使用 Webpacker gem与 Rails-UJS 一起用于 Javascript 资产.我想在我的一些模块中使用 Rails UJS,以便从一个函数提交表单:
i just switched to Rails 6 (6.0.0.rc1) which uses the Webpacker gem by default for Javascript assets together with Rails-UJS. I want to use Rails UJS in some of my modules in order to submit forms from a function with:
const form = document.querySelector("form")
Rails.fire(form, "submit")
在以前安装了 Webpacker 的 Rails 版本中,Rails
引用似乎在我的模块中全局"可用,但现在我在调用 Rails.fire
时得到了这个......
In former Rails versions with Webpacker installed, the Rails
reference seemed to be "globally" available in my modules, but now i get this when calling Rails.fire
…
ReferenceError: Rails is not defined
如何使 @rails/ujs
中的 Rails
可用于特定模块或所有模块?
How can i make Rails
from @rails/ujs
available to a specific or to all of my modules?
在我的设置下面...
app/javascript/controllers/form_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
// ...
submit() {
const form = this.element
Rails.fire(form, "submit")
}
// ...
}
app/javascript/controllers.js
// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.
import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"
const application = Application.start()
const context = require.context("controllers", true, /_controller\.js$/)
application.load(definitionsFromContext(context))
app/javascript/packs/application.js
require("@rails/ujs").start()
import "controllers"
谢谢!
推荐答案
在我的app/javascript/packs/application.js
中:
import Rails from '@rails/ujs';
Rails.start();
然后在我正在编写的任何模块、控制器、组件中:
and then in whatever module, controller, component I'm writing:
import Rails from '@rails/ujs';
这篇关于在 JS 模块中使用 Rails-UJS(带有 webpacker 的 Rails 6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!