iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
佛心分享-SideProject30

NUXT3xVUE3xPINIA: 從零開始寫電商系列 第 12

[Day 12] 資料控制中心: Store via Pinia

  • 分享至 

  • xImage
  •  

先說一下為什麼要用Pinia而不是VueX好了,因為用過後真的就回不去了,只要理解框架狀態管理的模式,剩下的真的就像在寫js那樣...當然習慣VueX的樣模式的人大有人在,我個人選的話會選Pinia。另外官方也提到Nuxt3開始不再提供VueX的integration了建議使用Pinia:

Pinia - the official Vue recommendation

目錄

  • Installtion
  • Setting
  • 寫一個store的範例:./stores/useTest.ts
  • 後記

Installtion

Pinia的配置也很簡單(npm這邊有個坑,最下面會說明),按照Pinia官網安裝:

npx nuxi@latest module add pinia
npm i pinia -f

配置 nuxt.config.js

下了上面的commands後,modules這邊會自動幫你寫好,所以也不用特別配置,檢查一下沒問題就好:

// nuxt.config.js
export default defineNuxtConfig({
  // ... other options
  modules: [
    // ...
    '@pinia/nuxt',
  ],
})

寫一個store的範例:./stores/useTest.ts

import { defineStore } from 'pinia';
const storeName = 'test';
export const useTest = defineStore(storeName, () => {

    return {
        
    }
});

後記

本來跟過去一樣按照NUXT3官網安裝:npm i pinia @pinia/nuxt,結果報錯@@:

npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: nuxt-app@undefined
npm error Found: vue@3.4.38
npm error node_modules/vue
npm error   peer vue@"^3.3.4" from @nuxt/vite-builder@3.13.0
npm error   node_modules/@nuxt/vite-builder
npm error     @nuxt/vite-builder@"3.13.0" from nuxt@3.13.0
npm error     node_modules/nuxt
npm error       nuxt@"^3.13.0" from the root project
npm error   peer vue@">=2.7 || >=3" from @unhead/vue@1.10.0
npm error   node_modules/@unhead/vue
...以下省略

查看了一輪,試了一些方式,最後看到Pinia官網說明給NUXT3專案使用的安裝方式就成功了。

接著,在寫useTest.ts的時候報錯,Pinia根本沒安裝好嘛(菸),爬了一下看到這篇回答說是因為npm8.x後跟pinia有一些相容性問題,也許用yarn, pnpm不會有這個問題吧?有人試過嗎?

murmur: 今天又想起當時在上課時老師一直強調:要習慣有問題,也要習慣解決問題


上一篇
[Day 11] Error handling
下一篇
[Day 13] Models - 建立資料模型的type
系列文
NUXT3xVUE3xPINIA: 從零開始寫電商17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言