首页 > 解决方案 > 什么是使用 Vue.js 组件在 Rails 中实现表单的干净、简单且推荐的方法

问题描述

随着网络上关于使用 vue 和一系列方法的 Rails 表单的不同文章,似乎对于什么是最优雅的解决方案存在很多困惑。我主要关心的是如何将数据/模型对象从 rails 视图传递到 vue 组件,但我也可以使用其他最佳实践。我宁愿坚持使用 rails 来获得尽可能多的功能,并且仅将 Vue 用于 javascript 的优点(在我目前的形式中,它现在只是客户端验证)。

这是我到目前为止所拥有的(我也使用Buefy作为组件库):

# app/views/organizations/new.html.erb

<%= form_with(model: @organization, local: true) do |form| %>
  <organization-create-new-form
    :data=<%= { organization: @organization }.to_json %>>
  </organization-create-new-form>
<% end %>

我将form_with标签保留在 rails 视图中,这样我就不需要在 vue 组件中处理 CSRF 令牌部分。

# organizationCreateNewForm.vue

<template>
<section class="hero is-bold is-fullheight">
  <div class="hero-body">
    <div class="container has-text-centered">
      <h1 class="title">
        Create a new workspace for your organization
      </h1>
      <h2 class="subtitle">
        Enter your organization name below
      </h2>
      <div class="columns">
        <div class="column is-half is-offset-one-quarter">
          <b-field>
            <b-input placeholder="Organization Name" size="is-large"></b-input>
          </b-field>

          <b-button type="is-primary" size="is-medium" native-type="submit">Continue</b-button>
        </div>
      </div>
    </div>
  </div>
</section>
</template>

<script>
export default {
  data () {
    return {
      organization: JSON.parse("still need to figure out how to get data here from rails view")
    }
  }
}
</script>
# application.js where `content` is the id of my top level div in my rails layout

import TurbolinksAdapter from 'vue-turbolinks'
import Vue from 'vue/dist/vue.esm'
import Buefy from 'buefy'
import '../stylesheets/application.scss'
import Vuelidate from 'vuelidate'

Vue.use(TurbolinksAdapter)
Vue.use(Buefy)
Vue.use(Vuelidate)

document.addEventListener('turbolinks:load', () => {
  const app = new Vue({
    el: '#content',
  })
})

我想弄清楚的事情:

是否有人使用最小的可重用设置来使用 vue 组件实现 Rails 表单。如果您可以分享相同的内容,那将非常有帮助!谢谢您的帮助!

标签: ruby-on-railsvue.jsvue-componentruby-on-rails-6

解决方案


推荐阅读