简体   繁体   English

Rails UJS 不使用 Rails 7 触发

[英]Rails UJS not firing with Rails 7

I upgraded my Rails application to Rails 7. I know that Turbolinks and Rails UJS actually are replaced by the Hotwire combination of Stimulus and Turbo in Rails 7, but I wanted to know whether I can still use UJS and if yes, why is it not working?我将我的 Rails 应用程序升级到 Rails 7。我知道 Turbolinks 和 Rails UJS 实际上已被 Rails 7 中 Stimulus 和 Turbo 的 Hotwire 组合取代,但我想知道我是否仍然可以使用 UJS,如果可以,为什么不能在职的?

My method that is not working looks like this:我的不起作用的方法如下所示:

  submit(event) {
    this.errorTarget.classList.add("hidden")
    Rails.fire(this.formTarget, "submit")
    console.log('hi')
  }

The console.log works. console.log 有效。 When I click on an element, it used to change with this code, but now it doesn't change anymore.当我点击一个元素时,它曾经用这个代码改变,但现在它不再改变了。 Rails.fire simply does not fire anymore and there is no error in the log or in the network part when I inspect the website. Rails.fire不再触发,当我检查网站时,日志或网络部分没有错误。

I feel like I am missing something crucial here, but I don't know what.我觉得我在这里遗漏了一些重要的东西,但我不知道是什么。

To add rails-ujs to Rails 7 you should to do following steps:要将 rails-ujs 添加到 Rails 7,您应该执行以下步骤:

  1. Pin it, to let the application know, which package to use.固定它,让应用程序知道要使用哪个 package。 Enter in bash:在 bash 中输入:
./bin/importmap pin @rails/ujs

And now you have in your config/importmap.rb file something like this:现在您的config/importmap.rb文件中有如下内容:

pin "@rails/ujs", to: "https://ga.jspm.io/npm:@rails/ujs@7.0.1/lib/assets/compiled/rails-ujs.js"
  1. Now include @rails/ujs to your javascript.现在将 @rails/ujs 包含到您的 javascript 中。 In file javascript/controllers/application.js add:在文件javascript/controllers/application.js 中添加:
import Rails from '@rails/ujs';

Rails.start();
  1. Restart your application server重启你的应用服务器

In addition to @ruslan-vallev 's answer, please be aware that they need to co-exist & odds are you will be using turbo.除了@ruslan-vallev 的回答,请注意它们需要共存,并且您很可能会使用涡轮增压。 consult this link regarding submission handlers请参阅有关提交处理程序的此链接

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

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