官網:Pinia | The intuitive store for Vue.js (vuejs.org)
Pinia是一個輕量級的狀態管理庫。Pinia可以處理大型項目中複雜的狀態管理需求,而父傳子、子傳父以及跨組件通信,可以解決一些簡單的狀態傳遞問題。
打開cmd 轉到當前項目目錄下,安裝命令:npm install pinia
修改main.js
import { createApp } from 'vue' //導入Pinia的createPinia方法,用於創建Pinia實例(狀態管理庫) import { createPinia } from 'pinia' import App from './App.vue' const pinia=createPinia(); const app=createApp(App); app.use(pinia); app.mount('#app');
使用:
添加一個共享的倉庫\vuedemo\src\stores\web.js
import { reactive, ref } from 'vue' import { defineStore } from 'pinia' //導出useWebStore export const useWebStore = defineStore('web', () => { //定義一個響應式對象,存儲網站信息 const web = reactive({ name: "張三", age: 22 }) //定義一個響應式引用,存儲用戶數 const users = ref(1000) //定義方法 const userAdd = () => { users.value++ } return { web, users, userAdd } })
app.vue
<script setup> //導入倉庫 import { useWebStore } from './stores/web'; const webStore = useWebStore() console.log("webStore.web:",webStore.web) console.log("webStore.users:",webStore.users) </script> <template> {{ webStore.web.name }}----{{ webStore.web.age }}---{{ webStore.users }} <br> <button @click="webStore.userAdd" >添加用戶</button> </template> <style scoped> </style>
Pinia數據持久化
官網:Home | pinia-plugin-persistedstate (prazdevs.github.io)
安裝命令:npm i pinia-plugin-persistedstate
修改main.js
import { createApp } from 'vue' //導入Pinia的createPinia方法,用於創建Pinia實例(狀態管理庫) import { createPinia } from 'pinia' //從 pinia-plugin-persistedstate 模塊中導入 piniaPluginPersistedstate import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' import App from './App.vue' const pinia=createPinia(); //將插件添加到 pinia 實例上 pinia.use(piniaPluginPersistedstate) const app=createApp(App); app.use(pinia); app.mount('#app');
web.js
import { reactive, ref } from 'vue' import { defineStore } from 'pinia' //導出useWebStore export const useWebStore = defineStore('web', () => { //定義一個響應式對象,存儲網站信息 const web = reactive({ name: "張三", age: 22 }) //定義一個響應式引用,存儲用戶數 const users = ref(1000) //定義方法 const userAdd = () => { users.value++ } return { web, users, userAdd } }, { //持久化存儲到 localStorage 中 persist: true })
npm run dev後,點擊按鈕,然後刷新頁面發現webStore.users並沒有變化。