代码之家  ›  专栏  ›  技术社区  ›  amit_saxena

使用Vue.js组件在rails中实现表单的干净、简单且推荐的方法是什么

  •  0
  • amit_saxena  · 技术社区  · 5 年前

    这是我现在所拥有的(我也在使用 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',
      })
    })
    

    我想弄明白的事情:

    • 将数据/对象从rails视图传递到组件的最佳方式是什么。很多在线教程都使用 getElementById 然后从属性中读取数据,并在初始化组件时将其解析到application.js文件中。当我想在组件内部执行时,这里的最佳实践是什么?解析在组件内部的何处(在什么触发器处)发生?
    • 将每个表单的所有json转换(在rails视图中)和解析(在vue组件中)抽象为简单内容的首选方法是什么?
    • 我仍然希望以常规rails表单(而不是ajax)的形式提交表单,我认为这将在当前结构中自动发生。使用turbolinks,正常表单提交看起来非常平滑。

    0 回复  |  直到 5 年前