Vue新的狀態(tài)管理庫(kù)Pinia入門教程
為什么最近Pinia會(huì)火起來(lái)呢,主要在于Vue3推出來(lái)的時(shí)候,Vuex對(duì)于Vue3的組合式Api支持的不是特別好,也就是在這個(gè)時(shí)候Pinia出現(xiàn)了。
前沿
Vue官方推薦的狀態(tài)管理庫(kù)是Vuex,那為什么最近Pinia會(huì)火起來(lái)呢,主要在于Vue3推出來(lái)的時(shí)候,Vuex對(duì)于Vue3的組合式Api支持的不是特別好,也就是在這個(gè)時(shí)候Pinia出現(xiàn)了,最重要的是,Pinia不但支持Vue3,同時(shí)還支持Vue2,這就厲害了,而且最新Vuex5的特性還是參考的Pinia
使用教程
官網(wǎng):https://pinia.vuejs.org/
github地址:https://github.com/vuejs/pinia
1、安裝
npm install pinia -S
2、vue中引入
// Vue3中引入使用 import { createPinia } from 'pinia' app.use(createPinia()) //Vue2中引入使用 import { createPinia, PiniaVuePlugin } from 'pinia' Vue.use(PiniaVuePlugin) const pinia = createPinia() new Vue({ ? el: '#app', ? // 其它配置項(xiàng) ? pinia, })
3、基本使用
// 定義store // stores/counter.js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { ? // 狀態(tài)值定義 ? state: () => { ? ? return { count: 0 } ? }, ? // 狀態(tài)更改方法定義 ? actions: { ? ? increment() { ? ? ? this.count++ ? ? }, ? }, }) // 在組件中使用 // 導(dǎo)入狀態(tài) import { useCounterStore } from '@/stores/counter' export default { ? setup() { ? ? // 初始化一個(gè)store實(shí)例 ? ? const counter = useCounterStore() ? ? // state更新 ? ? counter.count++ ? ?? ? ? // 或者調(diào)用方法更新 ? ? counter.increment() ? }, }
4、也可以像vuex一樣使用
const useCounterStore = defineStore('counter', { ? // 狀態(tài)值 ? state: () => ({ count: 0 }), ? // getter值 ? getters: { ? ? double: (state) => state.count * 2, ? }, ? // actions方法 ? // 注意pinia里沒(méi)有mutation ? actions: { ? ? increment() { ? ? ? this.count++ ? ? } ? } }) // 定義另外一個(gè)store const useUserStore = defineStore('user', { ? // ... }) export default { ? // computed里引入使用state里的值 ? computed: { ? ? ...mapStores(useCounterStore, useUserStore) ? ? ...mapState(useCounterStore, ['count', 'double']), ? }, ? // methods里使用action ? methods: { ? ? ...mapActions(useCounterStore, ['increment']), ? }, }
好了,Pinia的入門教程就講到這,是不是語(yǔ)法更加簡(jiǎn)潔
到此這篇關(guān)于Vue新的狀態(tài)管理庫(kù)Pinia入門教程的文章就介紹到這了,更多相關(guān)Vue Pinia內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端vue面試總問(wèn)watch和computed區(qū)別及建議總結(jié)
在現(xiàn)代前端的面試中,vue和react是面試過(guò)程中基本必問(wèn)的技術(shù)棧,其中Vue響應(yīng)式話題,watch和computed是面試官非常喜歡聊的主題,雖然watch和computed它們都用于監(jiān)聽數(shù)據(jù)的變化,但它們?cè)趯?shí)現(xiàn)原理、使用場(chǎng)景和行為上有著顯著的區(qū)別,本文將深入探討,并提供一些面試過(guò)程中的建議2023-10-10詳解VUE自定義組件中用.sync修飾符與v-model的區(qū)別
這篇文章主要介紹了詳解VUE自定義組件中用.sync修飾符與v-model的區(qū)別,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06vue實(shí)例成員?插值表達(dá)式?過(guò)濾器基礎(chǔ)教程示例詳解
這篇文章主要為大家介紹了vue實(shí)例成員?插值表達(dá)式?過(guò)濾器基礎(chǔ)教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-04-04vue實(shí)現(xiàn)自定義公共組件及提取公共的方法
這篇文章主要介紹了vue實(shí)現(xiàn)自定義公共組件及提取公共的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05解決ele ui 表格表頭太長(zhǎng)問(wèn)題的實(shí)現(xiàn)
這篇文章主要介紹了解決ele ui 表格表頭太長(zhǎng)問(wèn)題的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11