首页 > 解决方案 > 将 VueJS 时间输入传递给 Rails 输入

问题描述

我正在构建一个 Rails 应用程序并想添加一个时间跟踪器。用户应该能够记录时间(我工作了 3 个小时)并提交,或者他们应该能够启动计时器,等待,然后提交。我选择了 VueJS 来构建它,并成功地将 Vue 与我的 Rails 5 应用程序集成。

我在 Vue 中构建了一个简单的计时器(开始、停止、显示当前时间)并嵌入到我的页面中。现在我希望用户填写一些额外的字段并保存时间条目。

我试图从 Vue 数据中获取小时、分钟和秒的值,并使用v-models 将其连接到基本simple_form time字段,但由于rails自动将输入字段生成为time_entry_duration_4itime_entry_duration_5i,因此我很难连接数据。

我什至应该将 JS 数据推送到 Rails 表单中吗?我是否应该重建表单,使其全部在 Vue 中并始终以这种方式提交?

谢谢。

#time_entries/_form.html.haml

= simple_form_for(@time_entry) do |f|
  = f.error_notification
  = f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?

  .form-inputs.row
    .col
      = f.association :project, collection: Project.joins(:assigned_roles).where(assigned_roles: {team_member: current_user}).distinct, hint: "If this is blank, you're not currently assigned to any projects."
      = f.input :task, collection: TaskType::TASK_TYPES.sort {|a, b| a <=> b }
  .form-inputs.row
    // This is the Rails way of doing things and works, but I can't connect it to the v-model
    = f.input :duration, as: :time, wrapper_html: { class: 'col-6'}, default: Time.parse('0:00')
    .col-6.form-group
      .d-flex.flex-row.justify-content-between
        = f.label :duration, label: "Hours"
        = f.label :duration, label: "Minutes"
        = f.label :duration, label: "Seconds"

      .d-flex.flex-row.justify-content-between.align-items-center
        // This is my attempt to recreate the hours/min/seconds and bind to the v-model, but it doesn't submit
        = f.text_field :duration, "v-model" => "hours", class: 'form-control mx-1'
        = f.text_field :duration, "v-model" => "minutes", class: 'form-control mx-1'
        = f.text_field :duration, "v-model" => "seconds", class: 'form-control mx-1'
    = f.input :date, wrapper_html: { class: 'col-6'}

  .form-inputs.row
    .col
      = f.input :notes, placeholder: "What were you working on?"

  .form-actions
    = f.button :submit, class: 'btn btn-primary btn-block'

标签: ruby-on-railsvue.js

解决方案


您可以通过使用纯 html 编写输入来混合使用 rails 和 Vue:

  .col-6.form-group
    .d-flex.flex-row.justify-content-between
      = f.label :duration, label: "Hours"
      = f.label :duration, label: "Minutes"
      = f.label :duration, label: "Seconds"

    .d-flex.flex-row.justify-content-between.align-items-center
      input type="text" name='time_entry[duration(4i)]' v-model="hours" class='form-control mx-1'
      input type="text" name='time_entry[duration(5i)]' v-model="minutes" class='form-control mx-1'
      input type="text" name='time_entry[duration(6i)]' v-model="seconds" class='form-control mx-1'

推荐阅读