ViewComponent Contrib 使用指南

ViewComponent Contrib 使用指南

view_component-contrib A collection of extension and developer tools for ViewComponent view_component-contrib 项目地址: https://gitcode.com/gh_mirrors/vi/view_component-contrib

1. 项目介绍

ViewComponent Contrib 是一个为 ViewComponent 提供扩展和开发者工具的集合。它旨在简化 ViewComponent 的使用,提供更多的功能和模式,帮助开发者更高效地构建和维护 Rails 应用中的视图组件。

2. 项目快速启动

安装

首先,确保你已经安装了 Ruby on Rails 和 ViewComponent。然后,将 ViewComponent Contrib 添加到你的 Gemfile 中:

gem 'view_component-contrib'

运行 bundle install 安装依赖。

初始化

使用交互式生成器(自定义 Rails 模板)来快速启动 ViewComponent Contrib:

rails app:template LOCATION='https://github.com/palkan/view_component-contrib/blob/main/template.rb'

创建组件

创建一个新的组件:

rails generate component ExampleComponent

这将生成以下文件:

app/components/example_component/example_component.html.erb
app/components/example_component/example_component.rb

使用组件

在你的视图中使用新创建的组件:

<%= render ExampleComponent.new %>

3. 应用案例和最佳实践

国际化支持

ViewComponent Contrib 提供了内置的国际化支持。如果你使用 ViewComponentContrib::Base,你已经包含了翻译支持。否则,你需要手动包含模块:

class ApplicationViewComponent < ViewComponent::Base
  include ViewComponentContrib::TranslationHelper
end

你可以覆盖默认的命名空间和特定组件的作用域:

class ApplicationViewComponent < ViewComponentContrib::Base
  self.i18n_namespace = "my_components"
end

class SomeButton::Component < ApplicationViewComponent
  self.i18n_scope = %w[legacy button]
end

CSS 模块化

使用 postcss-modules 插件来隔离 CSS,确保类名在组件中是局部的,并在构建时生成唯一的类名:

<div class="<%= css_module_class('example-class') %>">
  <!-- 组件内容 -->
</div>

4. 典型生态项目

Dry-Initializer

ViewComponent Contrib 推荐使用 dry-initializer 来改进开发体验,将命令式的 #initialize 方法转换为声明式的方式:

class ExampleComponent < ViewComponent::Base
  extend Dry::Initializer

  option :title, default: proc { "Default Title" }
end

ViewComponentContrib::Preview

使用 ViewComponentContrib::Preview 类来减少样板代码,并提供一组有用的助手:

class ExampleComponentPreview < ViewComponentContrib::Preview::Base
  def default
    render_with_template
  end
end

通过这些工具和扩展,ViewComponent Contrib 帮助开发者更高效地构建和维护 Rails 应用中的视图组件。

view_component-contrib A collection of extension and developer tools for ViewComponent view_component-contrib 项目地址: https://gitcode.com/gh_mirrors/vi/view_component-contrib

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙天林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值