一文帶你搞懂Vue3中Pinia的使用
什么是Pinia
用官網(wǎng)的一句話來說:Pinia 是 Vue的專屬狀態(tài)管理庫
Pinia就是為vue3而生,當(dāng)然也支持vue2
Pinia VS Vuex
Pinia在使用上更簡單,更適合同組合式api和Typescript一同使用
安裝Pinia
npm install pinia # or yarn add pinia
在vue的main.js中使用
import { createApp } from 'vue' import App from './App.vue' import {createPinia} from "pinia"; const app = createApp(App) app.use(createPinia()) app.mount('#app')
使用Pinia
定義store
store通過defineStore()函數(shù)進行定義,可以定義多個store,但是定義每個store的時候必須要傳入一個唯一的id作為defineStore()的第一個參數(shù)
import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ user: { name: '張三' } }), getters: { userName: (state) => state.user.name, }, actions: { setName(name) { this.user.name = name }, }, })
也可以定義組合式api形式的store
ref()對應(yīng) state
- computed() 對應(yīng) getters
- function() 對應(yīng) actions
export const useUserStore = defineStore('user', () => { const user = ref({ name: '張三' }) const userName = computed(() => { return user.value.name }) function setName(name) { user.value.name = name } ? return { user, userName, setName } })
在vue組件中使用store
<template> <div> <div>用戶名: {{userName}}</div> <button @click="handleClick">設(shè)置用戶名</button> </div> </template> <script lang="ts" setup> import {useUserStore} from "../stores"; import {storeToRefs} from "pinia"; const store = useUserStore() // 將store中的state或者getter轉(zhuǎn)為響應(yīng)式變量 const {userName} = storeToRefs(store) // 將store中的action解構(gòu)出來 const {setName} = store const handleClick = () => { increment('李四') } </script> <style scoped lang="scss"> </style>
Pinia之state
state在store里面是一個返回初始狀態(tài)的函數(shù)
import { defineStore } from 'pinia' ???????interface User { name: string sex: number } const useUserStore = defineStore('user', { // 如果使用的是ts,使用箭頭函數(shù)可以自動推理出state返回狀態(tài)的類型 state: () => { return { isTest: false count: 1, userList: [] as User[], } }, })
訪問state
const store = useUserStore() ???????store.count++
重置store中的state
調(diào)用$reset()重置之后,state里的狀態(tài)會全部恢復(fù)為初始值
store.$reset()
修改state中的狀態(tài)
除了上面store.count++直接修改這種方式,還可以使用$patch函數(shù)同時修改多個狀態(tài)
store.$patch({ count: store.count + 1, isTest: true, }) // 傳入一個函數(shù) store.$patch((state) => { state.count = state.count + 1, state.isTest = true })
訂閱state
通過store的$subscribe函數(shù)可以監(jiān)聽state 的變化
store.$subscribe((mutation, state) => { console.log(mutation); console.log(state); })
mutation為修改state的方式,主要有三個屬性
1.type: direct | patch object | patch function
- direct:通過等號直接賦值的方式修改state的狀態(tài)時
- patch object :通過$patch函數(shù)修改并且傳入的參數(shù)為一個對象時
- patch function:通過$patch函數(shù)修改并且傳入的參數(shù)為一個函數(shù)時
2.storeId:定義當(dāng)前store時傳入的唯一id
3.payload:type為patch object 時,傳入的對象
Pinia之getter
getter完全等同于store中state的計算屬性,推薦使用箭頭函數(shù)來定義getter,并將state作為第一個參數(shù)。
在getter內(nèi)部可以通過this方位到整個store
定義getter
import { defineStore } from 'pinia' export const useUserStore = defineStore('user', { state: () => ({ user: { name: '張三' } }), getters: { userName: (state) => state.user.name, }, })
組合式api的形式定義getter
export const useUserStore = defineStore('user', () => { const user = ref({ name: '張三' }) // 相當(dāng)于getter中定義userName const userName = computed(() => { return user.value.name }) return { user, userName } })
向getter傳參
訪問getter時不能傳遞任何參數(shù),但是可以通過使getter返回一個接收參數(shù)的函數(shù)的形式來接收參數(shù)
getters: { userName: (state) => { return (before) => before + state.user.name }, }
訪問帶參getter
<script> export default { setup() { const store = useUserStore() return { getUserName: store.userName } }, } </script> <template> <p>{{ getUserName('Hi,') }}</p> </template>
Pinia之a(chǎn)ction
action相當(dāng)于組件的method,在store中定位為一個函數(shù)(可以是異步函數(shù)),主要用于處理業(yè)務(wù)邏輯,在action內(nèi)部同樣可以通過this訪問的整個store的屬性
import { defineStore } from 'pinia' ???????export const useUserStore = defineStore('user', { state: () => ({ user: { name: '張三' } }), actions: { setName(name) { this.user.name = name }, }, })
訪問action
export default { setup() { const store = useUserStore() store.setName('李四') return { } }, }
訂閱action
通過store的$onAction()函數(shù)來監(jiān)聽action執(zhí)行的相關(guān)信息.
$onAction()接收兩個參數(shù),第一個參數(shù)為一個鉤子函數(shù),會在action執(zhí)行之前調(diào)用此鉤子函數(shù);第二個參數(shù)是一個boolean類型的參數(shù),當(dāng)前組件被銷毀是傳入的鉤子函數(shù)是否繼續(xù)執(zhí)行,默認為false
const store = useUserStore() store.$onAction(({name, store, args, after, onError})=>{ console.log(`${name} 函數(shù)準備開始執(zhí)行`) console.log(`${name} 函數(shù)的參數(shù)為:${args}`) after(() => { console.log(`${name} 函數(shù)執(zhí)行完成`) }) }) // 手動刪除監(jiān)聽器 unsubscribe()
到此這篇關(guān)于一文帶你搞懂Vue3中Pinia的使用的文章就介紹到這了,更多相關(guān)Vue3 Pinia內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue?3.0?v-for中的Ref數(shù)組用法小結(jié)
在?Vue?2?中,在?v-for?里使用的?ref?attribute會用ref?數(shù)組填充相應(yīng)的?$refs?property,本文給大家介紹Vue?3.0?v-for中的Ref數(shù)組的相關(guān)知識,感興趣的朋友一起看看吧2023-12-12解決vite.config.js無法使用__dirname的問題
這篇文章主要介紹了解決vite.config.js無法使用__dirname的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10vue對象添加屬性(key:value)、顯示和刪除屬性方式
這篇文章主要介紹了vue對象添加屬性(key:value)、顯示和刪除屬性方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07vue2+springsecurity權(quán)限系統(tǒng)的實現(xiàn)
本文主要介紹了vue2+springsecurity權(quán)限系統(tǒng)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05