ruby-on-rails 如何在Rails 7中使用JavaScript?

uinbv5nw  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(114)

我希望在Rails应用程序中有一个可用于视图的JavaScript文件。

// app/javascript/custom/manage.js

document.body.style.backgroundColor = 'lightblue'
const test = document.getElementById('test')
# config/importmap.rb

pin_all_from "app/javascript/custom", under: "custom"
# app/views/locations/manage.html.erb

<%= javascript_include_tag "custom/manage", defer: true %>

当我回到manage视图时,我得到以下错误:

Uncaught SyntaxError: redeclaration of const test

我怀疑这是因为Turbo的工作方式。因为我尝试在application.js文件中注解它,错误消失了。

flmtquvp

flmtquvp1#

据我所知,你需要选择性导入模块功能
可以选择性地导入特定页面上的模块,使用content_for在视图顶部添加

<%# app/views/locations/manage.html.erb %>

<% content_for :custom_js do %>
  <%= javascript_import_module_tag "custom/manage" %>
<% end %>

在布局中

<%= javascript_importmap_tags %>
<%= yield(:custom_js) %>

javascript_importmap_tags应该是第一个

相关问题