Pinia 快速入門


 

Pinia 是什么?

Pinia 是一個用於 Vue 的狀態管理庫,類似 Vuex, 是 Vue 的另一種狀態管理方案
Pinia 支持 Vue2 和 Vue3

本文只講 Pinia 在 Vue3 中的使用, 在 Vue2 中使用略有差異,參考  官方文檔

Pinia 優勢

符合直覺,易於學習
極輕, 僅有 1 KB
模塊化設計,便於拆分狀態

安裝 Pinia

安裝需要 @next 因為 Pinia 2 處於 beta 階段, Pinia 2 是對應 Vue3 的版本

# 使用 npm
npm install pinia@next # 使用 yarn yarn add pinia@next

創建一個 pinia(根存儲)並將其傳遞給應用程序:

import { createPinia } from 'pinia'; app.use(createPinia());

核心概念與基本使用

Store

Store 是一個保存狀態和業務邏輯的實體,可以自由讀取和寫入,並通過導入后在 setup 中使用
創建一個 store

// store.js
import { defineStore } from "pinia"; // defineStore 調用后返回一個函數,調用該函數獲得 Store 實體 export const useStore = defineStore({ // id: 必須的,在所有 Store 中唯一 id: "myGlobalState", // state: 返回對象的函數 state: ()=> ({ count: 1 }), });

使用 Store

// xxx.vue
<template> <div> {{store.count}} </div> </template> <script> // 導入 Store, 使用自己的路徑 import { useStore } from "@/store/store.js"; export default { setup() { // 調用函數 獲得Store const store = useStore(); return { store } } } </script>

Getters

Pinia 中的 Getters 作用與 Vuex 中的 Getters 相同,但使用略有差異
Pinia 中的 Getters 直接在 Store 上讀取,形似 Store.xx,就和一般的屬性讀取一樣

Getter基本使用

Getter 第一個參數是 state,是當前的狀態,也可以使用 this.xx 獲取狀態
Getter 中也可以訪問其他的 Getter, 或者是其他的 Store
例子:
// 修改 store.js
import { defineStore } from "pinia"; import { otherState } from "@/store/otherState.js"; export const useStore = defineStore({ id: "myGlobalState", state: ()=> ({ count: 2 }), getters: { // 一個基本的 Getter: 計算 count 的平方 // 使用參數 countPow2(state) { return state.count ** 2; }, // 使用 this /* countPow2() { return this.count ** 2; }, */ // 簡單的 Getter 直接使用箭頭函數 // countPow2: state=> state.count ** 2 // 獲取其它 Getter, 直接通過 this countPow2Getter() { return this.countPow2; } // 使用其它 Store otherStoreCount(state) { // 這里是其他的 Store,調用獲取 Store,就和在 setup 中一樣 const otherStore = useOtherStore(); return otherStore.count; }, } }); // otherState.js import { defineStore } from "pinia"; export const useStore = defineStore({ id: "otherState", state: ()=> ({ count: 5 }), });

actions

Pinia 沒有 Mutations,統一在 actions 中操作 state,通過this.xx 訪問相應狀態
雖然可以直接操作 Store,但還是推薦在 actions 中操作,保證狀態不被意外改變
action 和普通的函數一樣
action 同樣可以像 Getter 一樣訪問其他的 Store,同上方式使用其它 Store,這里不在贅述,詳細請移步 官方文檔 Actions

action 基本使用

// store.js
export const useStore({ state: ()=> ({ count: 2, // ... }) // ... actinos: { countPlusOne() { this.count++; }, countPlus(num) { this.count += num; } } })

總結

Pinia 相比 Vuex 更加簡單,而且 Pinia 可以自由擴展 官方文檔 Plugins
Pinia 是符合直覺的狀態管理方式,讓使用者回到了模塊導入導出的原始狀態,使狀態的來源更加清晰可見
Pinia 的使用感受類似於 Recoil,但沒有那么多的概念和 API,主體非常精簡,極易上手(Recoil 是 Facebook 官方出品的用於 React 狀態管理庫,使用 React Hooks 管理狀態)
Pinia 2 目前還在 Beta 狀態,不建議在生產環境中使用,不過相信穩定了以后會成為 Vue 生態中另一大狀態管理方案


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM