1.pinia的簡單介紹
Pinia最初是在2019年11月左右重新設計使用Composition API的 Vue 商店外觀的實驗,
從那時起,最初的原則相同,但 Pinia 適用于 Vue 2 和 Vue 3 ,
并且不需要你使用組合 API,
除了安裝和SSR之外,還有其他的 API是一樣的,
并且這些針對 Vue 3 ,并在必要時提供 Vue 2 的相關注釋,
以便 Vue 2 和 Vue 3 的用戶可以閱讀!
2.為什么要使用Pina?
Pinia 是 Vue 的存盤庫,
允許您跨組件/頁面共享狀態,
如果您的組合 API,您可能會認為您可以使用簡單的export const state = reactive({})
這對于單頁應用程式來說是正確的,
但如果它是服務器端的外觀,將您的應用程式顯示給安全漏洞,
但即使在小型單頁應用程式中,您也可以從使用 Pinia 中獲得好處:
1.開發工具支持
2.動作、追蹤的跟蹤
3.熱模塊更換
4.為 JS 用戶提供適當功能的 TypeScript 支持或自動完成
5.服務器端渲染支持
安裝
npm install pinia --save
3.創建檔案夾和檔案-存放資料
在新建 src/store目錄并在其下面創建 index.ts檔案,并匯出這個檔案
// src/store/index.ts下的代碼
import { createPinia } from 'pinia'
const store = createPinia()
export default store
在 main.ts 中引入
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
<!-- 引入 -->
import store from "./store/index"
<!-- 使用store -->
createApp(App).use(router).use(store).mount('#app')
需求描述
假設我們現在有好幾個模塊,有user模塊,admin模塊,
我們想對這模塊中的資料進行管理,
為了管理方便,后面易于維護,我們決定將這些模塊進行拆分,
于是我們在store下創建 user.ts 檔案,管理這個user模塊的資料,
user.ts下的資料
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
sex:'男',
work:'寫代碼',
heigt:'1.70cm'
}
},
})
defineStore的介紹
defineStore 接收兩個引數.
第一個引數:必須是唯一的,多個模塊千萬千萬不能重名,
因為Pinia 會把所有的模塊都掛載到根容器上
第二個引數是一個物件,里面的選項state和 Vuex 差不多
4.獲取store中值的第一種方法
<template>
<div >
<h2> 學習pinia </h2>
<div> {{ userStore }} </div>
<div>姓名:{{ userStore.name }}</div>
<div>性別:{{ userStore.sex }}</div>
<div>作業:{{ userStore.work }}</div>
<div>身高:{{ userStore.heigt }}</div>
</div>
</template>
<script setup lang='ts'>
// 引入store中暴露出去的方法
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
</script>

獲取store中值的第二種方法-computed
<template>
<div >
<h2> 學習pinia </h2>
<div>姓名:{{useStoreName}}</div>
<div>性別:{{useStoreSex}}</div>
</div>
</template>
<script setup lang='ts'>
// 引入store中暴露出去的方法
import { computed } from 'vue'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
// 使用 computed取獲取值
const useStoreName = computed(() => userStore.name)
const useStoreSex = computed(() => userStore.sex)
</script>

提出問題
如果物件上有多個屬性,可以進行結構嗎?
可以的!
使用 pinia 提供的 storeToRefs
我們來看下怎去使用
5.pinia 提供的 storeToRefs進行結構
<template>
<div >
<h2> 學習pinia </h2>
<div>姓名:{{ asName }}</div>
<div>性別:{{ mysex }}</div>
<div>作業:{{ work }}</div>
<div>身高:{{ heigt }}</div>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
// asName 和 mysex 是我取的別名
const { name : asName ,sex:mysex, work, heigt } = storeToRefs(userStore)
</script>

6.如何修改 state 中的資料
修改 state 中的資料,可以通過 actions 下的方法,
然后呼叫 updataName 就可以取修改 state中的name值了
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
sex:'男',
work:'寫代碼',
heigt:'1.70cm'
}
},
// actions 可以修改state中的值,這里面提供方法
actions:{
// 修改name中的資料
updataName(name:string){
this.name=name
},
},
})
呼叫方法,修改state中的name
<template>
<div >
<h2> 學習pinia </h2>
<div>姓名:{{ asName }}</div>
<div>性別:{{ mysex }}</div>
<div>作業:{{ work }}</div>
<div>身高:{{ heigt }}</div>
<el-button type="primary" @click="changeHander">修改name</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
// asName 和 mysex 是我取的別名
const { name : asName ,sex:mysex, work, heigt } = storeToRefs(userStore)
const changeHander=()=>{
userStore.updataName('小玉兔')
// 這樣我發現也可以,但是不推薦這樣使用,
// 統一通過 actions 中的方法去修改值
userStore.work='我換作業了'
}
</script>

7.getters的使用
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
sex:'男',
work:'寫代碼',
heigt:'1.70cm',
age:26,
}
},
// actions 可以修改state中的值,這里面提供方法
actions:{
// 修改name中的資料
updataName(name:string){
this.name=name
},
},
// Getter 完全等同于 Store 狀態的計算值
getters:{
// 將姓名進行更改
getName: (state) => {
return state.name + 'hahha~!'
}
}
})
//使用的頁面.vue
<template>
<div >
<h2> 學習pinia </h2>
<div>姓名:{{ asName }}</div>
<div>性別:{{ mysex }}</div>
<div>作業:{{ work }}</div>
<div>身高:{{ heigt }}</div>
<div>身高:{{ age }}</div>
<!-- 這里就直接使用了getters中的方法 -->
姓名:{{ userStore.getName }}
<el-button type="primary" @click="changeHander">修改name</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
// asName 和 mysex 是我取的別名
const { name : asName ,sex:mysex,
work, heigt,age
} = storeToRefs(userStore)
const changeHander=()=>{
userStore.updataName('小玉兔')
}
</script>

對于getters的使用的說明
Getter 完全等同于 Store 狀態的計算值 computed.
并不會影響原始資料
9.異步actions-設定state中的值
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
// 引入介面
import { getUser } from "../https/api";
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
}
},
// actions 可以修改state中的值,這里面提供方法
actions:{
// 修改name中的資料 同步
updataName(name:string){
this.name=name
},
// 異步-獲取遠端的資料
loadUserList(){
getUser({}).then(res=>{
this.likelist = res
})
}
// 使用await和async 第二種方法
// async loadUserList(){
// const list = await getUser({})
// console.log('list',list)
// this.likelist = list
// }
},
})
使用的頁面
<template>
<div >
<h2> 學習pinia </h2>
資料 {{ userStore.likelist}}
<el-button type="primary" @click="changeHander">獲取遠端資料</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
const changeHander=()=>{
// 異步呼叫
userStore.loadUserList() // 加載所有資料
}

10.actions 中互相呼叫方法
很多時候,我們可能會出現 actions中互相去呼叫方法,
這個時候怎么去處理呢?
通過this.方法名(引數)
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
// 引入介面
import { getUser } from "../https/api";
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
}
},
// actions 可以修改state中的值,這里面提供方法
actions:{
// 修改name中的資料 同步
updataName(name:string){
this.name=name
},
// 異步-獲取遠端的資料
loadUserList(){
getUser({}).then(res=>{
this.likelist = res
this.sayHi('互相呼叫方法')
})
},
sayHi(mess:string){
console.log('loadUserList方法中呼叫了sayHi',mess)
}
},
})
使用的頁面.vue
<template>
<div >
<h2> 學習pinia </h2>
資料 {{ userStore.likelist}}
<el-button type="primary" @click="changeHander">獲取遠端資料</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
const changeHander=()=>{
// 異步呼叫
userStore.loadUserList() // 加載所有資料
}
</script>

11.資料持久化-sessionStorage 或 localStorage
我們都知道,vuex重繪后,資料會丟失,
這個時候我們需要將資料進行持久化,
我們可以考慮sessionStorage或者localStorage
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
// 引入介面
import { getUser } from "../https/api";
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
// 資料持久化使用的是sessionStorage
name: sessionStorage.getItem('name') ? sessionStorage.getItem('name') : '于途',
likelist:[],
}
},
actions:{
// 修改name中的資料 同步
updataName(name:string){
sessionStorage.setItem('name', name)
this.name=name
},
},
})
<template>
<div >
<h2> 學習pinia </h2>
姓名 {{ userStore.name}}
<el-button type="primary" @click="changeHander">該變值</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
import { useUserStore } from '../../store/user'
const userStore = useUserStore()
const changeHander=()=>{
// 異步呼叫
userStore.updataName('我改變了姓名')
}
</script>

12.跨模塊修改資料
雖然我不建議跨模塊修改資料,
因為這樣可能會導致你的應用資料流向變得難以理解,
但是有些時候確實需要跨模塊修改資料,
那么pinia怎么去處理跨模塊修資料呢?
下面我們一起來探索跨模塊修改資料!
假設admin模塊需要去修改user模塊中的資料
admin.ts代碼如下
//src/store/admin.ts 檔案
import { defineStore } from 'pinia'
// 引入user模塊
import { useUserStore } from './user'
export const adminUserStore = defineStore({
id: 'adminkey',
actions:{
// 通過引入的useUserStore模塊,然后去觸發它里面對應的方法,
editUserModuleValue(name:string){
// userStore可以看見整個user模塊中的資料和方法
let userStore=useUserStore()
console.log('userStore',userStore)
userStore.updataName(name)
}
},
})
user.ts代碼
//src/store/user.ts 檔案
import { defineStore } from 'pinia'
// 引入介面
export const useUserStore = defineStore({
id: 'userkey', // id必填,且需要唯一
// state是存放資料的
state: () => {
return {
name: '于途',
likelist:[],
sex:'男',
work:'寫代碼',
heigt:'1.70cm'
}
},
actions:{
// 修改name中的資料 同步
updataName(name:string){
this.name=name
},
},
})
頁面的使用
<template>
<div >
<h2> 學習pinia </h2>
姓名 {{ userStore.name}}
<el-button type="primary" @click="changeHander">該變值</el-button>
</div>
</template>
<script setup lang='ts'>
import { storeToRefs } from 'pinia'
// 引入admin模塊
import { adminUserStore } from '../../store/admin'
// 引入user模塊
import { useUserStore } from '../../store/user'
const adminStore = adminUserStore()
const userStore = useUserStore()
// dmin模塊需要去修改user模塊中的資料
const changeHander=()=>{
adminStore.editUserModuleValue('資料資料')
}
</script>

尾聲
如果你覺得我寫的不錯的話,可以給我推薦、打賞、評論!
上一個給我打賞的小伙伴都已經找到女朋友了!
咦!你不信,不信你給我打賞看一下!
保準你追到到喜歡的Ta!
你不會追,哎!難受,
我教你,你可以這樣說:
小生不才,斗膽-問,不知姑娘是否心系他人,
感情之事,在下不敢兒戲!
如若姑娘早已心系他人,那在下便不再打擾,
如若有所唐突還望姑娘多加體諒!
若姑娘非我良人,那在下就不庸人自惱,
在下怕越陷越深,還望姑娘盡早告知!話已至此,我便先在此謝過!
拿去不謝!回頭告訴我結果啊!
咦!抓住一個沒有打賞的小伙伴!
遇見問題,這是你成長的機會,如果你能夠解決,這就是識訓,
作者:明月人倚樓出處:https://www.cnblogs.com/IwishIcould/
想問問題,打賞了卑微的博主,求求你備注一下的扣扣或者微信;這樣我好聯系你;(っ??ω??)っ???!
如果覺得這篇文章對你有小小的幫助的話,記得在右下角點個“推薦”哦,或者關注博主,在此感謝!
萬水千山總是情,打賞5毛買辣條行不行,所以如果你心情還比較高興,也是可以掃碼打賞博主(っ??ω??)っ???!
想問問題,打賞了卑微的博主,求求你備注一下的扣扣或者微信;這樣我好聯系你;(っ??ω??)っ???!
支付寶
微信
本文著作權歸作者所有,歡迎轉載,未經作者同意須保留此段宣告,在文章頁面明顯位置給出原文連接 如果文中有什么錯誤,歡迎指出,以免更多的人被誤導,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464066.html
標籤:JavaScript
上一篇:存盤桶策略允許寫入訪問,盡管策略中只有getObject
下一篇:async和await的實作原理
