我试图让刺激控制器屏蔽 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();
}
}
你不能使用
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]);
}
}