網(wǎng)站首頁 編程語言 正文
pinia的常用知識點(diǎn)及搭配“script setup”的使用
- 前言
- 一、安裝pinia
- 二、創(chuàng)建一個(gè)store
- 三、Store 間的相互訪問
- 四、pinia 中常用的內(nèi)置方法
- 五、pinia的分模塊使用例子
- 六、補(bǔ)充:composition API 寫法
前言
對比于vuex,新的Vue狀態(tài)管理庫pinia更加的輕量。并且具有更加明顯的優(yōu)勢,包括有:拋棄傳統(tǒng)的 mutation,通過action對同異步進(jìn)行操作簡化狀態(tài)管理庫;不需要嵌套模塊,讓代碼扁平化;更好的TypeScript支持;更友好的調(diào)用方式等。同時(shí)結(jié)合vue3.2推出的setup語法糖使用會(huì)得到更加友好的體驗(yàn)。一、安裝pinia
- npm 安裝
npm install pinia
- main.ts下導(dǎo)入pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
createApp(App).use(createPinia()).mount('#app')
二、創(chuàng)建一個(gè)store
項(xiàng)目結(jié)構(gòu):
- 導(dǎo)入 “defineStore()”
- 為每個(gè) store 規(guī)定唯一的命名
- 按需創(chuàng)建 state、getters、actions 部分操作
import { defineStore } from 'pinia'
export const mainStore = defineStore('main', {
state: () => ({
// 在該項(xiàng)中可以自定義狀態(tài)數(shù)據(jù)
// ......
sum:0
}),
getters: {
// 該項(xiàng)等同于 Store 狀態(tài)的 計(jì)算值,類似于計(jì)算屬性
// ......
getDoubleSum(state) {
return state.sum*2
}
}
actions: {
// 相當(dāng)于組件中的 methods,用于定義和處理業(yè)務(wù)邏輯
//.......
addSum(value: number) {
this.sum += value
}
}
})
注:this 可以訪問到自身的 store 實(shí)例
- Pinia 創(chuàng)建的 Store 動(dòng)作被派發(fā)為普通的函數(shù)調(diào)用,不再需要使用dispatch 方法或MapAction 輔助函數(shù)
<template>
<div>
<p>sum:{{useMainStore.sum}}</p>
<p>doubleSum:{{useMainStore.getDoubleSum}}</p>
<button @click="useMainStore.addSum(1)">sum+1</button>
</div>
</template>
<script setup lang="ts">
import { mainStore } from "../store/index";
const useMainStore = mainStore()
</script>
三、Store 間的相互訪問
- 調(diào)用對應(yīng)創(chuàng)建的 “Store方法” 即可獲取實(shí)例使用
例如:
import { defineStore } from 'pinia'
export const mainStore = defineStore('main', {
state: () => ({
sum: 0,
}),
})
export const otherStore = defineStore('other', {
state: () => ({
doubleSum: 0
}),
getters: {
updateDoubleSum(state) {
// 獲取 "mainStore" 的實(shí)例,并使用其中的 sum 狀態(tài)
const useMainStore = mainStore()
state.doubleSum = useMainStore.sum * 2
return state.doubleSum
}
}
})
四、pinia 中常用的內(nèi)置方法
- 重置狀態(tài)到初始值
- 通過調(diào)用 store 上的 $reset() 方法可將狀態(tài)重置
const store = useStore()
store.$reset()
- 一次更改多個(gè)狀態(tài)
- 通過調(diào)用 store 上的 $patch 方法,支持使用部分 “state” 對象同時(shí)應(yīng)用多個(gè)更改
const store = useStore()
store.$patch({
counter: store.counter + 1,
name: 'Abalam',
})
五、pinia的分模塊使用例子
項(xiàng)目結(jié)構(gòu):
- index.ts 文件:
import { createPinia } from 'pinia'
import useUserStore from "./modules/user/index";
import useAppStore from "./modules/app/index";
const pinia = createPinia()
export { useUserStore, useAppStore }
export default pinia
- main.ts 文件:
import { createApp } from 'vue'
import App from './App.vue'
import pinia from "./pinia";
createApp(App).use(pinia).mount('#app')
- 模塊文件,這里展示 user 模塊:
- types.ts 文件:
export type RoleType = '' | 'admin' | 'user'
export interface UserState {
name?: string;
email?: string;
phone?: string;
introduction?: string;
role: RoleType;
}
- index.ts 文件:
import { defineStore } from "pinia";
import type { UserState, RoleType } from "./types";
import { getUserInfo } from "@/network/test";
const useUserStore = defineStore('user',{
state:():UserState=>({
name: undefined,
email: undefined,
phone: undefined,
introduction: undefined,
role:''
}),
getters:{
userInfo(state:UserState):UserState {
return {...state}
}
},
actions:{
setRole(role: RoleType) {
this.role = role
},
setInfo(partial: Partial<UserState>) {
this.$patch(partial);
},
resetInfo() {
this.$reset()
},
async info() {
const res:any = await getUserInfo();
this.setInfo(res.data);
},
}
})
export default useUserStore
六、補(bǔ)充:composition API 寫法
上面的store均使用 options API 的寫法,以下我們改為使用 composition API 模式定義store,改寫法更符合Vue3 setup的編程模式,讓結(jié)構(gòu)更加扁平化,寫法轉(zhuǎn)化如下:
- 使用 ref、reactive 定義的變量代替 options API中的state;
- 使用 computed 代替 options API中的getters;
- 直接書寫 函數(shù)代替 options API中的actions;
現(xiàn)在我們使用上面的寫法把“目錄一”創(chuàng)建的store改為 composition API 的寫法:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const mainStore = defineStore('main', ()=>{
const sum = ref<number>(0)
const doubleSum = computed<number>(() => sum.value * 2)
const addSum = (value: number) => {
sum.value += value
}
return { sum, doubleSum, addSum }
})
提示:文章到此結(jié)束,文章僅為個(gè)人學(xué)習(xí)記錄,若有不足還請大家指出。
原文鏈接:https://blog.csdn.net/weixin_53068161/article/details/126785114
- 上一篇:沒有了
- 下一篇:沒有了
相關(guān)推薦
- 2022-12-23 C++?Boost?Parameter超詳細(xì)講解_C 語言
- 2022-04-11 解決辦法:error: failed to push some refs to 'https://g
- 2022-03-17 .NET?6開發(fā)TodoList應(yīng)用實(shí)現(xiàn)結(jié)構(gòu)搭建_實(shí)用技巧
- 2022-10-10 python使用pandas讀寫excel文件的方法實(shí)例_python
- 2022-12-05 python中的單下劃線與雙下劃線以及絕對導(dǎo)入與相對導(dǎo)入_python
- 2022-06-14 詳解Python中生成隨機(jī)數(shù)據(jù)的示例詳解_python
- 2022-10-25 python庫-dotenv包?及?.env配置文件詳解_python
- 2022-09-16 詳解C++?中?shared_ptr?weak_ptr_C 語言
- 欄目分類
-
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支