You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rails中为Stimulus.js控制器的Tom Select配置maxOptions

解决Tom Select仅显示50条选项的问题

方法一:直接在配置中固定设置上限

你只需要在Tom Select的配置对象config里添加maxOptions参数,把值设为你需要的数量(比如你的285条,或者用Infinity显示所有选项)。修改后的connect方法代码如下:

connect() {
  this.element.setAttribute( "autocomplete", "random" );

  var config = {
    plugins: ['clear_button'],
    render: {
      option: this.render_option,
      item: this.render_option,
    },
    // 添加这一行,设置显示的最大选项数
    maxOptions: 285 // 或者用 Infinity 显示所有选项
  }

  if(this.hasOptionsValue) {
    config.options = this.optionsValue
  }

  new TomSelect(this.element, config)
}

方法二:通过Stimulus Value动态配置(更灵活)

如果想在视图层灵活调整这个上限,不用每次改JS代码,可以给控制器添加一个maxOptionsValue,这样就能通过HTML的data属性传递值:

  1. 修改控制器代码,添加maxOptionsValue并在配置中使用:
import { Controller } from "@hotwired/stimulus"
import TomSelect      from "tom-select"

// Connects to data-controller="ts--select"
export default class extends Controller {
  static values = {
    url: String,
    options: Array,
    maxOptions: Number // 添加这个值定义
  }

  connect() {
    this.element.setAttribute( "autocomplete", "random" );

    var config = {
      plugins: ['clear_button'],
      render: {
        option: this.render_option,
        item: this.render_option,
      }
    }

    if(this.hasOptionsValue) {
      config.options = this.optionsValue
    }

    // 如果传递了maxOptions值,就设置到配置里
    if(this.hasMaxOptionsValue) {
      config.maxOptions = this.maxOptionsValue
    } else {
      // 没传递的话可以设个默认值,比如285或者Infinity
      config.maxOptions = 285
    }

    new TomSelect(this.element, config)
  }

  render_option(data, escape) {
    if(data.sub)
      return `
      <div>
        <div class="text">${escape(data.text)}</div>
        <div class="sub">${escape(data.sub)}</div>
      </div>`
    else
      return `<div>${escape(data.text)}</div>`
  }

}
  1. 在Rails视图中使用时,通过data属性传递值:
<select data-controller="ts--select" data-ts--select-max-options-value="285">
  <!-- 选项内容 -->
</select>

这样不管是固定值还是动态调整,都能解决仅显示50条的问题,而且符合Stimulus的最佳实践。

内容的提问来源于stack exchange,提问作者3BB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:16:16