Vue新的狀態(tài)管理庫Pinia入門教程
為什么最近Pinia會火起來呢,主要在于Vue3推出來的時候,Vuex對于Vue3的組合式Api支持的不是特別好,也就是在這個時候Pinia出現(xiàn)了。
前沿
Vue官方推薦的狀態(tài)管理庫是Vuex,那為什么最近Pinia會火起來呢,主要在于Vue3推出來的時候,Vuex對于Vue3的組合式Api支持的不是特別好,也就是在這個時候Pinia出現(xiàn)了,最重要的是,Pinia不但支持Vue3,同時還支持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', ? // 其它配置項 ? 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() { ? ? // 初始化一個store實例 ? ? 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里沒有mutation ? actions: { ? ? increment() { ? ? ? this.count++ ? ? } ? } }) // 定義另外一個store const useUserStore = defineStore('user', { ? // ... }) export default { ? // computed里引入使用state里的值 ? computed: { ? ? ...mapStores(useCounterStore, useUserStore) ? ? ...mapState(useCounterStore, ['count', 'double']), ? }, ? // methods里使用action ? methods: { ? ? ...mapActions(useCounterStore, ['increment']), ? }, }
好了,Pinia的入門教程就講到這,是不是語法更加簡潔
到此這篇關(guān)于Vue新的狀態(tài)管理庫Pinia入門教程的文章就介紹到這了,更多相關(guān)Vue Pinia內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
前端vue面試總問watch和computed區(qū)別及建議總結(jié)
在現(xiàn)代前端的面試中,vue和react是面試過程中基本必問的技術(shù)棧,其中Vue響應(yīng)式話題,watch和computed是面試官非常喜歡聊的主題,雖然watch和computed它們都用于監(jiān)聽數(shù)據(jù)的變化,但它們在實現(xiàn)原理、使用場景和行為上有著顯著的區(qū)別,本文將深入探討,并提供一些面試過程中的建議2023-10-10詳解VUE自定義組件中用.sync修飾符與v-model的區(qū)別
這篇文章主要介紹了詳解VUE自定義組件中用.sync修飾符與v-model的區(qū)別,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06vue實例成員?插值表達式?過濾器基礎(chǔ)教程示例詳解
這篇文章主要為大家介紹了vue實例成員?插值表達式?過濾器基礎(chǔ)教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04