如何在Rails6內經過Webpacker使用JavaScript; flatpicker日期時間組件選擇器

如何在Rails6內經過Webpacker使用JavaScript;  

Rails6默認再也不使用asset pipeline,改用Webpacker。javascript

文件結構變化:css

  • 配置文件: webpacker.yml
  • package.json查看安裝的js庫,可使用yarn命令或者npm
  • app/assets/javascript不會再generate。
  • app/javascript/packs/application.js:packs文件夾管理獨立安裝的包。

 下圖是默認生成的文件夾。包含了rails UJS庫, turbolinks, atcivestorage, channelshtml

添加了channels文件夾。java

 

如何安裝一個packer:webpack

# 例如
rails webpacker:install:stimulus
Appending Stimulus setup code to /Users/.../tailwindapp/app/javascript/packs/application.js
      append app/javascript/packs/application.js
# 增長了一行代碼
import "controllers"
Creating controllers directory
      create  app/javascript/controllers
      create  app/javascript/controllers/hello_controller.js
      create  app/javascript/controllers/index.js
Installing all Stimulus dependencies
         run  yarn add stimulus from "."
#安裝依賴包,能夠在yarn.lock中看到詳細說明

 

 

使用Flatpickr

一個輕量化的datetime picker。web

包括使用JS和CSSnpm

https://flatpickr.js.org/json

安裝:app

# using npm install
npm i flatpickr --save

# 其餘
yarn add flatpickr

#cdn也能夠

use

推薦直接使用元素,或者選擇器:post

// If using flatpickr in a framework, its recommended to pass the element directly
flatpickr(element, {});

// Otherwise, selectors are also supported
flatpickr("#myID", {}); // creates multiple instances flatpickr(".anotherSelector");

 

Rails中的使用

1. 生成一個Post

  下面的命令仍然會生成assetpipeline的文件: stylesheets/scaffolds.scss,若是不使用就刪除掉。

rails g scaffold Post title publish_date:date

2. yarn add flatpickr

javascript/packs/application.js內添加:

import flatpickr from "flatpickr";
#只使用flatpickr的CSS樣式
require("flatpickr/dist/flatpickr.css")
#或者使用不一樣的樣式主題
#require("flatpickr/dist/themes/light.css")

document.addEventListener("turbolinks:load", () => {
flatpickr("[data-behavior='flatpickr']", {
altInput: true,
altFormat: "F j, Y",
dateFormat: "Y-m-d"
})
})

在application.html.erb添加:(使用webPacker CSS)

<%= stylesheet_pack_tag 'application', media: "all", ...%>

在對應的視圖文件內添加:

<div>
  <%= form.text_field :publish_date, data: {behavior: 'flatpickr'}%>
</div>

#生成<input data-behavior="flatpickr" type="hidden" name="post[publish_date]" id="post_publish_date" class="flatpickr-input">
相關文章
相關標籤/搜索