Vue項(xiàng)目新一代狀態(tài)管理工具Pinia的使用教程
前言
Pinia官網(wǎng)介紹說:Pinia 是 Vue 的存儲(chǔ)庫,它允許您跨組件/頁面共享狀態(tài)。Vuex同樣可以作為狀態(tài)管理工具,那么兩者有什么區(qū)別呢?
Pinia與Vuex的區(qū)別
- pinia只有store、getter、actions,么有mutations,簡化了狀態(tài)管理的操作
- pinia模塊劃分不需要modules,
- pinia自動(dòng)化代碼拆分
- pinia對(duì)ts支持很好以及vue3的composition API
- pinia體積更小,性能更好
使用Pinia
defineStore( )
方法的第一個(gè)參數(shù):容器的名字,名字必須唯一,不能重復(fù)defineStore( )
方法的第二個(gè)參數(shù):配置對(duì)象,放置state,getters,actionsstate
屬性: 用來存儲(chǔ)全局的狀態(tài)getters
屬性: 用來監(jiān)視或者說是計(jì)算狀態(tài)的變化的,有緩存的功能actions
屬性: 修改state全局狀態(tài)數(shù)據(jù),可以是異步也可以是同步Pinia
可以用于vue2.x也可以用于vue3.x中
安裝
yarn add pinia -S
main.js
引入
import {createApp} from "vue" import App from "./app.vue" import store from "./store/index.js" const app = createApp(App); const store = createPinia(); app.use(store).mount("#app")
在store文件夾下新建test.js
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存儲(chǔ)配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
在用actions的時(shí)候,不能使用箭頭函數(shù),因?yàn)榧^函數(shù)綁定是外部的this。actions里的this指向當(dāng)前store
在store文件夾下新建index.js,便于管理
import {createPinia} from "pinia" const store = createPinia(); export default store
新建A.vue
組件,引入store模塊和storeToRefs
方法storeToRefs
:解構(gòu)store
中的數(shù)據(jù),使之成為響應(yīng)式數(shù)據(jù)
<template> <div> <div> {{tname}}</div> <div> {{tid}}</div> <div> tnum: {{tnum}}</div> <div> {{tchangeNum}}</div> <div><button @click="tchangeName">修改</button></div> <div> <button @click="treset">重置</button></div> <div @click="actionsBtn">actionsBtn</div> </div> </template>
<script setup> import { storeToRefs } from 'pinia' import { useStore } from '../store/user' import { useTest } from '../store/test.js' const testStore = useTest(); let { tname, tchangeNum, tnum } = storeToRefs(testStore) </script>
直接修改數(shù)據(jù)的兩種方式
直接修改數(shù)據(jù)與使用$path
修改數(shù)據(jù)相比,官方已經(jīng)明確表示$patch
的方式是經(jīng)過優(yōu)化的,會(huì)加快修改速度,對(duì)程序的性能有很大的好處。所以如果你是多條數(shù)據(jù)同時(shí)更新狀態(tài)數(shù)據(jù),推薦使用$patch
方式更新。
雖然可以直接修改,但是出于代碼結(jié)構(gòu)來說, 全局的狀態(tài)管理還是不要直接在各個(gè)組件處隨意修改狀態(tài),應(yīng)放于actions
中統(tǒng)一方法修改(piain沒有mutation)。
//直接修改數(shù)據(jù) tchangeName(){ tname.value = "測試數(shù)據(jù)"; tnum.value++; } //當(dāng)然也可以使用`$path`批量修改 tchangeName(){ testStore.$path(state=>{ state.tname = "測試數(shù)據(jù)"; state.value = 7; }) }
使用actions修改數(shù)據(jù)
直接調(diào)用actions
中的方法,可傳參數(shù)
const actionsBtn = (){ testStore.addNum(5) }
重置state中數(shù)據(jù)
store
中有$reset
方法,可以直接對(duì)store
中數(shù)據(jù)重置
const treset = (){ testStore.$reset() }
Pinia持久化存儲(chǔ)
實(shí)現(xiàn)持久化存儲(chǔ),需要配合以下插件使用
yarn add pinia-plugin-persist
配置store
文件夾下的index.js
文件,引入pinia-plugin-presist
插件
import {createPinia} from "pinia" import piniaPluginPresist from "pinia-plugin-presist" const store = createPinia(); store.use(piniaPluginPresist) export default store
配置stroe文件夾下的test.js文件,使用presist
屬性進(jìn)行配置
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存儲(chǔ)配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
enable:true
,開啟持久化存儲(chǔ),默認(rèn)為使用sessionStorage
存儲(chǔ)- -
strategies
,進(jìn)行更多配置 - -
key
,不設(shè)置key時(shí),storage的key為definePinia
的第一個(gè)屬性,設(shè)置key值,則自定義storage的屬性名
- -
storage:localStorage
,設(shè)置緩存模式為本地存儲(chǔ)paths
,不設(shè)置時(shí)對(duì)state
中的所用數(shù)據(jù)進(jìn)行持久化存執(zhí),設(shè)置時(shí)只針對(duì)設(shè)置的屬性進(jìn)行持久化存儲(chǔ)
Pinia模塊化實(shí)現(xiàn)
模塊化實(shí)現(xiàn)即在store對(duì)要使用的模塊新建一個(gè)js文件,比如user.js
文件。然后配置內(nèi)容跟其他模塊一樣,根據(jù)自己需求進(jìn)行設(shè)置,然后在對(duì)應(yīng)頁面引入。
Pinia中store之間互相調(diào)用
比如:test.js
獲取user.js
中state
的name
屬性值,在test.js
引入user.js
import { defineStore } from 'pinia' import { userStore } from "./user.js" export const useTest = defineStore("testId", { state: () => { return { tid: "111", tname: "pinia", tnum: 0 } }, getters: { tchangeNum() { console.log('getters') return this.tnum + 100 } }, actions: { tupNum(val) { console.log('actions') this.tnum += val; }, getUserData() { console.log(useStore().name); return useStore().name; }, }, persist: { //走的session enabled: true, strategies: [ { key: "my_testId", storage: localStorage, paths: ['tnum'] } ] } })
user.js
中
import { defineStore } from 'pinia' export const useStore = defineStore('storeId', { state: () => { return { num: 0, name: '張三' } } })
A.vue
組件中,調(diào)用test.js
中getUserData
方法就可以得到uesr.js
中的name
值
const actionBtn = () => { testStore.getUserData() };
總結(jié)
到此這篇關(guān)于Vue項(xiàng)目新一代狀態(tài)管理工具Pinia使用的文章就介紹到這了,更多相關(guān)Vue Pinia狀態(tài)管理工具使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue中JSON文件神奇應(yīng)用fetch、axios異步加載與模塊導(dǎo)入全指南詳細(xì)教程
在Vue中使用JSON文件有多種方式,包括使用fetch方法加載JSON文件、使用axios庫加載JSON文件,以及將JSON文件導(dǎo)入為模塊,這篇文章主要介紹了Vue中JSON文件神奇應(yīng)用fetch、axios異步加載與模塊導(dǎo)入全指南詳細(xì)教程,需要的朋友可以參考下2024-01-01vue實(shí)現(xiàn)側(cè)邊欄導(dǎo)航效果
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)側(cè)邊欄導(dǎo)航效果,右側(cè)顯示對(duì)應(yīng)內(nèi)容,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10vue.js如何更改默認(rèn)端口號(hào)8080為指定端口的方法
本篇文章主要介紹了vue.js如何更改默認(rèn)端口號(hào)8080為指定端口的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07vue中使用Echarts?map圖實(shí)現(xiàn)下鉆至縣級(jí)的思路詳解
這篇文章主要介紹了vue中使用Echarts?map圖實(shí)現(xiàn)下鉆至縣級(jí),需要注意的是,因?yàn)槲沂侵苯訌?vue-cli2?直接跳到?vue-cli4?,還奇怪怎么讀取不到JSON,查找后才知道?vue-cli3?往后的項(xiàng)目基礎(chǔ)架構(gòu)對(duì)比舊版本有些區(qū)別,感興趣的朋友跟隨小編一起看看吧2022-01-01vue.js的computed,filter,get,set的用法及區(qū)別詳解
下面小編就為大家分享一篇vue.js的computed,filter,get,set的用法及區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03Vue.js綁定HTML class數(shù)組語法錯(cuò)誤的原因分析
Vue.js綁定HTML class數(shù)組語法錯(cuò)誤有哪些原因?qū)е碌哪?,該如何解決呢?下面小編給大家分享Vue.js綁定HTML class數(shù)組語法錯(cuò)誤的原因分析,感興趣的朋友一起看看吧2016-10-10詳解VUE 對(duì)element-ui中的ElTableColumn擴(kuò)展
本篇文章主要介紹了詳解VUE 對(duì)element-ui中的ElTableColumn擴(kuò)展,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03