添加 imaskjs with rails and hotwire stimulus 但它不起作用

问题描述 投票:0回答:1

我试图让刺激控制器屏蔽 2 个输入字段,“总收入”和“运营成本”以在两个字段上显示千位分隔符。我试过 imaskjs 和 stimulusjs,但我不知道为什么它根本不起作用。

<div class='' data-controller="currency">

    <%= f.label :gross_revenue %>

    <%= f.number_field :gross_revenue, class: '', data: { currency_target: "gross" } %>

  </div>

下面是我的控制器

import { Controller } from "@hotwired/stimulus"

import IMask from "imask"


// data-controller="currency"

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

  connect() {

    this.mask = IMask(this.currencyTarget, { 
      mask: Number,
      thousandsSeparator: ',',
    });

  }

  disconnect() {

    this.mask?.destroy();

  }

}
javascript ruby-on-rails stimulusjs hotwire imaskjs
1个回答
0
投票

你不能使用

number
字段:

请注意
如果将遮罩应用于输入元素,则必须使用

type="text"
。不支持其他类型。

https://imask.js.org/guide.html

<div data-controller="currency">
  <%= f.text_field :gross_revenue, data: { currency_target: "gross" } %>
  <!-- NOTE: target name is "gross"                          ^^^^^ -->
</div>

修复目标名称(您也应该将其重命名为更通用的名称):

import { Controller } from "@hotwired/stimulus";
import IMask from "imask";

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

  connect() {
    this.mask = IMask(this.grossTarget, {
      mask: Number,
      thousandsSeparator: ",",
    });
  }
}

您也可以只使用控制器元素:

<%= f.text_field :gross_revenue, data: {
  controller: "mask",
  mask_type_value: "currency"
} %>
// app/javascript/controllers/mask_controller.js

import { Controller } from "@hotwired/stimulus";
import IMask from "imask";

const maskOptions = {
  currency: { mask: Number, thousandsSeparator: "," },
};

export default class extends Controller {
  static values = { type: String };

  connect() {
    IMask(this.element, maskOptions[this.typeValue]);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.