iT邦幫忙

2023 iThome 鐵人賽

DAY 17
0
影片教學

Nuxt 3 快速入門系列 第 17

[影片教學] Nuxt 3 使用 Pinia 進行狀態管理

  • 分享至 

  • xImage
  •  

Yes

👆建議你可以使用影片子母畫面功能或全螢幕播放來獲得最佳的觀賞體驗,👇下方是本篇教學的相關筆記。


安裝 Pinia 與 Nuxt Pinia 模組

在專案中安裝 Pinia 與 Nuxt Pinia 模組

npm install -D pinia @pinia/nuxt

如果使用 NPM 安裝套件的過程中有遇到依賴樹解析問題可以添加 --force

開啟專案下 nuxt.config.ts 檔案,配置使用 Nuxt Pinia 模組

export default defineNuxtConfig({
  modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt'],
  devtools: { enabled: true }
})

建立第一個 Store

stores 目錄下建立一個檔案 ./stores/counter.js

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count += 1
    },
    decrement() {
      this.count -= 1
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2
  }
})

建立路由頁面

pages 目錄下建立一個檔案 ./pages/index.vue

<template>
  <div class="bg-white py-24">
    <div class="flex flex-col items-center">
      <h1 class="text-6xl font-semibold text-gray-800">這裡是首頁</h1>
      <div class="my-4 flex flex-col space-y-4">
        <NuxtLink to="/counter">前往 /counter</NuxtLink>
        <NuxtLink to="/show">前往 /show</NuxtLink>
      </div>
    </div>
  </div>
</template>

修改 app.vue 頁面:

<template>
  <div>
    <NuxtPage />
  </div>
</template>

建立使用 Store 的頁面

pages 目錄下建立一個檔案 ./pages/counter.vue

<template>
  <div class="bg-white py-24">
    <div class="flex flex-col items-center">
      <ClientOnly>
        <span class="text-9xl font-semibold text-sky-600">{{ counterStore.count }}</span>
      </ClientOnly>
      <div class="mt-8 flex flex-row">
        <button
          class="font-base mx-2 rounded-full bg-sky-500 px-4 py-2 text-xl text-white hover:bg-sky-600 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2"
          @click="counterStore.increment"
        >
          增加
        </button>
        <button
          class="font-base mx-2 rounded-full bg-sky-500 px-4 py-2 text-xl text-white hover:bg-sky-600 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2"
          @click="counterStore.decrement"
        >
          減少
        </button>
      </div>
      <div class="mt-8">
        <NuxtLink to="/">回首頁</NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup>
const counterStore = useCounterStore()
</script>

pages 目錄下建立一個檔案 ./pages/show.vue

<template>
  <div class="bg-white py-24">
    <div class="flex flex-col items-center">
      <p class="mt-4 text-slate-500">這裡顯示的是 counterStore 的 doubleCount</p>
      <ClientOnly>
        <span class="text-9xl font-semibold text-emerald-600">{{ counterStore.doubleCount }}</span>
      </ClientOnly>
      <div class="mt-8">
        <NuxtLink to="/">回首頁</NuxtLink>
      </div>
    </div>
  </div>
</template>

<script setup>
const counterStore = useCounterStore()
</script>

設定 stores 目錄的自動載入

開啟專案下 nuxt.config.ts 檔案,添加 imposrs.dir 選項,將專案下的 stores 目錄添加於可以被自動載入

export default defineNuxtConfig({
  modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt', '@pinia-plugin-persistedstate/nuxt'],
  devtools: { enabled: true },
  imports: {
    dirs: ['stores']
  }
})

安裝 Pinia 持久化插件

在專案中安裝 Pinia 持久化插件

npm install -D @pinia-plugin-persistedstate/nuxt

開啟專案下 nuxt.config.ts 檔案,配置使用 Pinia 持久化插件的 Nuxt 整合模組

export default defineNuxtConfig({
  modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt', '@pinia-plugin-persistedstate/nuxt'],
  devtools: { enabled: true },
  imports: {
    dirs: ['stores']
  }
})

設定 counterStore 持久化選項 persist,修改 ./stores/counter.js 檔案:

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count += 1
    },
    decrement() {
      this.count -= 1
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2
  },
  persist: {
    key: 'counter',
    storage: persistedState.localStorage
  }
})

感謝大家的閱讀,歡迎大家給予建議與討論,也請各位大大鞭小力一些:)
如果對這個 Nuxt 3 系列感興趣,可以訂閱接收通知,也歡迎分享給喜歡或正在學習 Nuxt 3 的夥伴。

範例程式碼

參考資料


上一篇
[影片教學] Nuxt 3 狀態管理 (State Management)
下一篇
[影片教學] Nuxt 3 Runtime Config & App Config
系列文
Nuxt 3 快速入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言