雖然我們已經做過幾次 LiveView 了,但是跟 gen.html 一樣, Phoenix 一樣有提供 gen.live
來讓我們快速產生一個標準的 LiveView CRUD
mix phx.gen.live Products Product products name quantity:integer note:text

輸入之後他會回應
Add the live routes to your browser scope in lib/blog_web/router.ex:
    live "/products", ProductLive.Index, :index
    live "/products/new", ProductLive.Index, :new
    live "/products/:id/edit", ProductLive.Index, :edit
    live "/products/:id", ProductLive.Show, :show
    live "/products/:id/show/edit", ProductLive.Show, :edit
Remember to update your repository by running migrations:
    $ mix ecto.migrate
他替我們產生了幾個 LiveView 的路徑要放進 Router 裡
另外因為也有產生 migration 也是要執行一下 mix ecto.migrate
如果是第一次執行 LiveView 的產生器還會產生一些共用的 Component
像是 modal,並且會自動在所有的 LiveView 裡面都可以拿得到
我們要跑 migration 前他編譯的時候,或是編輯器的檢查也會檢查到我們之前做的 modal component 跟他衝突了
我們在這邊可以幫我們的 modal 改名(記得使用的地方也要改)
Router 貼上之後就可以啟動伺服器去看看長怎樣了http://localhost:4000/products


如果有去看產生出來的寫法,會發現跟我之前的做法差很多,因為 LiveView 非常彈性,掌握寫法之後,可以依照需求去做自己要的變化。
在最後我們來改一下首頁吧
一直有新頁面要一直打網址也很煩
編輯 lib/blog_web/templates/page/index.html.heex
<section>
  <h2>Controller + View</h2>
  <ul>
    <li>
      <%= link("筆記 (Note) CRUD (產生器)", to: Routes.note_path(@conn, :index)) %>
    </li>
    <li>
      <%= link("文章 (Post) CRUD", to: Routes.post_path(@conn, :index)) %>
    </li>
  </ul>
</section>
<section>
  <h2>LiveView</h2>
  <ul>
    <li>
      <%= link("LiveView 文章 (Post) CRUD", to: Routes.post_index_path(@conn, :index)) %>
    </li>
    <li>
      <%= link("即時多人聊天室", to: Routes.chat_room_path(@conn, :chat_room)) %>
    </li>
    <li>
      <%= link("產品 (Product) CRUD (產生器)", to: Routes.product_index_path(@conn, :index)) %>
    </li>
  </ul>
</section>

我不知道大家是不是也是這樣,但我會期待點 Logo 會回到首頁,
但是預設的頁面點 Logo 一直到 Phoenix 的網站我覺得有點煩
更改的地方可以在 lib/blog_web/templates/layout/root.html.heex 找到