RoR, Stimulus.js: 一个简单的输入计算?

RoR, Stimulus.js: A simple input calculation?

我是刺激计划的新手。我正在尝试添加 number/currency 输入并在另一个字段中显示(这些字段是十进制属性),因为用户输入他们的值,但我无法让它工作。

这里我想加上'land cost' + 'prof services' 显示在'total cost' 字段

我的控制器:

cost_calculate.controller.js

import { Controller } from 'stimulus'

export default class extends Controller {

  static targets = [ 'landCost', 'profServices', 'totalCost' ]

  updateTotalCost () {
    const totalCost = this.landCost() + this.profServices() 
    this.totalCostTarget.value = Number(totalCost).toFixed(2)
  }

  landCost () {
    return parseInt(this.landCostTarget)
  }

  profServices () {
    return parseInt(this.profServicesTarget)
  }

  totalCost () {
    return parseInt(this.totalCostTarget)
  }
}

我的表格:

<%= simple_form_for @project, html: { "data-controller" => "cost-calculate" }, url: wizard_path(step, project_id: @project.id) do |f| %> 
    
      
<%= f.text_field :land_cost, data: { target: 'cost-calculate.landCost', action: "change->cost-calculate#updateTotalCost" }, class: "project-dropdown-width" %>
    
<%= f.text_field :prof_services, data: { target: 'cost-calculate.profServices', action: "change->cost-calculate#updateTotalCost" }, class: "project-dropdown-width" %> 
    
<%= f.text_field :total_cost, data: { target: 'cost-calculate.totalCost' }, label: false, class: "project-dropdown-width" %>
                      
<% end %>

它一直在 'totalCost' 字段中打印 NaN。我不完全相信我的代码在控制器中是正确的,或者查看我想做什么。

比如我想实现这个只是把两个字段加在一起

https://ngaunhien.net/blog/simple-input-calculation-with-stimulusjs

将不胜感激任何指导。 ty.

您应该使用值和 parse,如果不存在值,则设置默认值 0。

您应该将 controller 修改为

import { Controller } from 'stimulus'

export default class extends Controller {
  
  static targets = [ 'landCost', 'profServices', 'totalCost' ]
  
  updateTotalCost () {
    const totalCost = this.landCost() + this.profServices()
    this.totalCostTarget.value = Number(totalCost).toFixed(2)
  }

  landCost () {
    return parseInt(this.landCostTarget.value || 0)
  }

  profServices () {
    return parseInt(this.profServicesTarget.value || 0)
  }

  totalCost () {
    return parseInt(this.totalCostTarget.value)
  }
}