Maple楓
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Nuxt3 Pinia Plugin Persistedstate [Pinia Plugin Persistedstate](https://prazdevs.github.io/pinia-plugin-persistedstate/) 讓你可以將 Pinia 的狀態持久化儲存在瀏覽器的 Cookie、SessionStorage 或 LocalStorage 中。 --- ## 安裝 ```bash npm install pinia @pinia/nuxt pinia-plugin-persistedstate ``` --- ## Nuxt 配置 在 `nuxt.config.js` 中加入以下設置: ```javascript export default { modules: [ '@pinia/nuxt', 'pinia-plugin-persistedstate' ], imports: { // 設定要 auto imports 的資料夾 dirs: ['stores'] } } ``` ### 常見問題處理 **錯誤:** 在 Nuxt 3.7.0+ 版本可能出現 `[vite-node] [ERR_LOAD_URL]` 錯誤 :::spoiler 示意圖 ![截圖 2024-01-31 下午3.37.40](https://hackmd.io/_uploads/r1tyYuvcT.png) ::: **解決方式:** 在 `nuxt.config.js` 加入 transpile 配置 ```javascript export default { // ...其他配置 build: { transpile: ['pinia-plugin-persistedstate'] } } ``` **參考資料:** [GitHub Issue #236](https://github.com/prazdevs/pinia-plugin-persistedstate/issues/236) --- ## Store 定義 在 `/stores/` 目錄下建立 store 檔案: ```javascript import { defineStore } from 'pinia' // 方法一: Options API 語法 export const useCounterStore = defineStore('counter', { state: () => ({ message: 'Hello World!!' }), getters: { // getters 定義 }, actions: { setNewText(newText) { this.message = newText } }, persist: { storage: persistedState.sessionStorage } }) // 方法二: Composition API 語法 (推薦) export const useCounterStore = defineStore( 'counter', () => { // State const count = ref(0) const message = ref('pinia') const objUser = ref({ id: 1, name: 'Pinia' }) // Actions const addCount = () => { count.value++ } const setNewText = (newText) => { message.value = newText } return { count, message, objUser, addCount, setNewText } }, { // Persist 配置 persist: { key: 'counter-store', // 自訂儲存 key storage: process.client ? persistedState.sessionStorage : null, paths: ['count', 'message'] // 只儲存指定的狀態 } } ) ``` --- ## Persist 配置選項 ### 1. 基本啟用 ```javascript persist: true ``` **預設行為:** - 儲存位置: Cookie - 儲存 Key: Store 的 ID (defineStore 第一個參數) - 儲存範圍: 整個 state --- ### 2. 自訂 Key ```javascript persist: { key: 'my-custom-key' } ``` 覆寫預設的儲存 key 名稱。 --- ### 3. Storage 選項 ```javascript persist: { storage: persistedState.sessionStorage } ``` **可用選項:** - `persistedState.cookies` (預設) - `persistedState.localStorage` - `persistedState.sessionStorage` **重要提醒:** 為避免 SSR Hydration 錯誤,建議使用: :::spoiler error message Hydration completed but contains mismatches. ![截圖 2024-01-30 下午1.11.57](https://hackmd.io/_uploads/SkpCBWIq6.png) ::: ```javascript storage: process.client ? persistedState.sessionStorage : null ``` --- ### 4. Cookie 進階配置 ```javascript persist: { storage: persistedState.cookiesWithOptions({ sameSite: 'strict', maxAge: 60 * 60 * 24 * 7, // 7 天 secure: true, path: '/' }) } ``` 選項參考 [Nuxt useCookie 文檔](https://nuxt.com/docs/api/composables/use-cookie#options) --- ### 5. 部分狀態儲存 ```javascript persist: { paths: ['count', 'message'] } ``` 只儲存指定的狀態屬性,其他屬性不會被持久化。 --- ### 6. Debug 模式 ```javascript persist: { debug: true } ``` 啟用後會在 Console 輸出錯誤訊息,方便除錯。 --- ## 在組件中使用 ```htmlembedded <template> <div> <ClientOnly> <div> <p>{{ counter.message }}</p> <button @click="counter.setNewText('New text!')"> 更新文字 </button> </div> <div> <p>計數: {{ counter.count }}</p> <button @click="counter.addCount"> 增加計數 </button> </div> </ClientOnly> </div> </template> <script setup> const counter = useCounterStore() </script> ``` ### Hydration 錯誤處理 如果遇到 `Hydration completed but contains mismatches` 錯誤: **方法一:** 使用 `<ClientOnly>` 組件包裹使用 store 的部分 **方法二:** 修改 storage 配置 (推薦) ```javascript storage: process.client ? persistedState.sessionStorage : null ``` --- ## 參考資料 - [Pinia Plugin Persistedstate 官方文檔](https://prazdevs.github.io/pinia-plugin-persistedstate/) - [GitHub Issue #218 - Customize persist option](https://github.com/prazdevs/pinia-plugin-persistedstate/issues/218) - [Nuxt 3 ClientOnly 使用教學](https://ithelp.ithome.com.tw/articles/10327918) - [IT邦幫忙 - Pinia Plugin Persistedstate 教學](https://ithelp.ithome.com.tw/articles/10332698) --- ## 完整配置範例 ```javascript export const useUserStore = defineStore( 'user', () => { const userInfo = ref(null) const token = ref('') const preferences = ref({}) const login = (info) => { userInfo.value = info } const logout = () => { userInfo.value = null token.value = '' } return { userInfo, token, preferences, login, logout } }, { persist: { key: 'user-session', storage: process.client ? persistedState.localStorage : null, paths: ['userInfo', 'token'], // 不儲存 preferences debug: import.meta.env.DEV } } ) ``` --- > **提示:** 敏感資訊 (如 token) 建議加密後再儲存,或考慮使用 httpOnly Cookie。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully