ruby-on-rails - 什么是使用 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',
})
})
我想弄清楚的事情:
- 将数据/对象从 Rails 视图传递到组件的最佳方式是什么。许多在线教程
getElementById
在初始化组件时使用然后从属性中读取数据并在其 application.js 文件中解析它。当我想在组件内执行此操作时,这里的最佳实践是什么?解析发生在组件内部的什么位置(在什么触发条件下)? - 将每个表单的所有 json 转换(在 rails 视图中)和解析(在 vue 组件中)抽象为简单的东西的任何首选方法?
- 我仍然想将表单作为常规 Rails 表单(而不是 ajax)提交,我认为这会在当前结构中自动发生。使用 turbolinks 正常的表单提交看起来很流畅。
是否有人使用最小的可重用设置来使用 vue 组件实现 Rails 表单。如果您可以分享相同的内容,那将非常有帮助!谢谢您的帮助!
解决方案
推荐阅读
- angular - 为什么我的 ngrx Effect 将字符串参数转换为数组?
- node.js - desktopCapturer 示例...如何使其适用于特定应用程序
- graphql - 是否自动提供了 GraphQL 的参数?
- python - Python 3.8 中 unittest 的奇怪之处 - 未检测到测试
- php - 如何将类添加到 php echo 语句?
- opencart-3 - Opencart 3x 菜单版
- node.js - 在 Node 中使用 TypeScript 解析不同级别的键值/值嵌套 JSON
- javascript - 如何使用 moment.js 在 2 个不同时区中获取同一日期的 unix 时间戳?
- javascript - 将 ref 转发到 react.FC 给出类型错误:类型'IntrinsicAttributes & Props & { children :? 反应节点}
- python - 画布内的 tkinter 框架未扩展到填充区域