首先,需要安装 @hotwired/stimulus 和 @hotwired/turbo。

然后,可以通过以下步骤实现多级 Cascader:

  1. 创建一个 Cascader 控制器:
import { Controller } from "@hotwired/stimulus";
import { Turbo } from "@hotwired/turbo";

export default class extends Controller {
  static targets = ["select"];

  connect() {
    this.initialize();
  }

  initialize() {
    this.selectTargets.forEach((select) => {
      select.addEventListener("change", () => {
        this.handleChange(select);
      });
    });
  }

  handleChange(select) {
    const value = select.value;
    const target = select.dataset.target;
    const nextTarget = document.querySelector(target);

    Turbo.fetch(`/data/${value}.json`).then((response) => {
      response.json().then((data) => {
        this.updateOptions(nextTarget, data);
      });
    });
  }

  updateOptions(select, options) {
    select.innerHTML = "";
    options.forEach((option) => {
      const optionElement = document.createElement("option");
      optionElement.value = option.value;
      optionElement.innerText = option.label;
      select.appendChild(optionElement);
    });
  }
}
  1. 在 HTML 中创建 Cascader 组件:
<div data-controller="cascader">
  <select data-target="cascader.select">
    <option value="">请选择</option>
    <option value="1">选项1</option>
    <option value="2">选项2</option>
    <option value="3">选项3</option>
  </select>
  <select data-target="cascader.select" data-cascader-target="#select2"></select>
  <select data-target="cascader.select" data-cascader-target="#select3"></select>
</div>

<select id="select2"></select>
<select id="select3"></select>
  1. 创建数据文件:

在 public/data 文件夹中创建选项的 JSON 文件,例如:

[
  { "value": "1-1", "label": "选项1-1" },
  { "value": "1-2", "label": "选项1-2" }
]
  1. 运行应用程序:

在终端中运行 npm startyarn start,然后在浏览器中打开应用程序,即可看到多级 Cascader 组件。

hotwiredstimulus 和 hotwiredturbo 实现像element-plus 一样的多级Cascader 级联选择器

原文地址: https://www.cveoy.top/t/topic/Fwr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录