我正在尝试在我的Rails 7应用上创建一个随输入搜索的搜索框。输入-点击-回车搜索可以工作,并且它在一个turbo框架中加载,但是js驱动的随输入搜索功能被破坏了。搜索框的事件侦听器根本没有启动. -.. -.当我选择框并输入时,浏览器的网络选项卡或JS控制台上什么也没有出现。
下面是部分搜索表单:
<div>
<%= search_form_for @q, data: { controller: "form-submission", turbo_frame: "companies", turbo_action: "advance" } do |f| %>
<%= f.search_field :search_multi, placeholder: "Search", class: "form-control search-box", data: { action: "input->form-submission#search" } %>
<% end %>
</div>
应用程序/javascript/控制器/表单提交控制器.js:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
search() {
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.element.requestSubmit()
}, 200)
}
}
应用程序/javascript/控制器/index.js:
// Import and register all your controllers from the importmap under controllers/*
import { application } from "controllers/application"
// Eager load all controllers defined in the import map under controllers/**/*_controller
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!)
// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading"
// lazyLoadControllersFrom("controllers", application)
配置/导入Map.rb
pin "application", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "popper", to: 'popper.js', preload: true
pin "bootstrap", to: 'bootstrap.min.js', preload: true
我试过Chrome和Safari浏览器。
我甚至用以下代码重新构建了我的Rails应用程序安装,然后将我所有的代码复制回它:rails new app --database=postgresql --asset-pipeline=sprockets --javascript=importmap
在JS控制台上:getEventListeners($("#q_search_multi"))
没有显示任何内容。
我也试过bin/rails assets:clobber && bin/rails assets:precompile
。
1条答案
按热度按时间3wabscal1#
今天我从头开始重建应用程序并确定了原因:我在app/app/views/layouts/application. html. erb中遗漏了
<%= javascript_importmap_tags %>
。* 叹气 * 吸取了教训。下面是完整的application.html.erb:欢迎阅读本指南,了解如何构建随输入随搜索的搜索框:https://www.colby.so/posts/instant-search-with-rails-6-and-hotwire