将VueJS时间输入传递到Rails输入

时间:2019-02-20 14:46:38

标签: ruby-on-rails vue.js

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

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

我尝试仅从Vue数据中获取小时,分钟和秒的值,并使用v-model将其连接到基本的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'

1 个答案:

答案 0 :(得分:1)

您可以通过使用纯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'