Pinia是一个用于Vue的状态管理库,类似Vuex,是Vue的另一种状态管理方案 Pinia支持Vue2和Vue3引用尤雨溪的话:pinia会替代vuex吗 很大概率,都是coreteam成员,讨论结果未来形态会很像pinia,新东西都写在pinia里,如果开发一个新项目,如果使用ts,推荐使用pinia。 官网链接:官方文档 Github链接:GithubPinia和Vuex比的优势符合直觉,易于学习极轻,仅有1KB模块化设计,便于拆分状态Pinia可以自由扩展官方文档PluginsPinia的使用安装Pinia使用npmnpminstallpinianextv2:应用于vue3中npminstallpinialatestv1:应用于v2中使用yarnyarnaddpinianext 提示:pinianext安装将会安装v2的版本,如果你想要在vue2中使用,需要安装v1:pinialatest和vuecompositionapi。这里不做介绍了。 创建一个pinia(根储存)并挂载到app上vue3中import{createPinia}frompiniaapp。use(createPinia())vue2中import{createPinia,PiniaPlugin}frompiniaVue。use(PiniaPlugin)constpiniacreatePinia()newVue({el:app,otheroptions。。。。。。notethesamepiniainstancecanbeusedacrossmultipleVueappsonthesamepagepinia,})如何定义一个store? pinia通过使用一个方法defineStore()来定义store,但是要注意的,store必须要有唯一的名字。import{defineStore}frompiniauseStorecouldbeanythinglikeuseUser,useCartthefirstargumentisauniqueidofthestoreacrossyourapplicationexportconstuseStoredefineStore(main,{otheroptions。。。})或者exportconstuseStoredefineStore({id:必须的,在所有Store中唯一id:main,其他配置})使用storedemo。vuetemplate{{store。count}}templateState 最简单的使用方式stateconststoreuseStore()store。counter重置stateconststoreuseStore()store。reset() 同vuex一样,在使用的时候也可以直接使用mapState遍历state属性(只读)import{mapState}frompiniaexportdefault{computed:{givesaccesstothis。counterinsidethecomponentsameasreadingfromstore。counter。。。mapState(useStore,〔counter〕)sameasabovebutregistersitasthis。myOwnName。。。mapState(useStore,{myOwnName:counter,youcanalsowriteafunctionthatgetsaccesstothestoredouble:storestore。counter2,itcanhaveaccesstothisbutitwontbetypedcorrectly。。。magicValue(store){returnstore。someGetterthis。counterthis。double},}),},} 通过mapWritableState()函数可以对state进行修改import{mapWritableState}frompiniaexportdefault{computed:{givesaccesstothis。counterinsidethecomponentandallowssettingitthis。countersameasreadingfromstore。counter。。。mapWritableState(useStore,〔counter〕)sameasabovebutregistersitasthis。myOwnName。。。mapWritableState(useStore,{myOwnName:counter,}),},} 这里注意这个方法对数组元素不生效,官网说明如下图: 使用patch可以进行state值的更新,并且支持多个值同时操作。store。patch({counter:store。counter1,name:Abalam,}) 通过subscribe()完成对值变化的监听。cartStore。subscribe((mutation,state){import{MutationType}frompiniamutation。typedirectpatchobjectpatchfunctionsameascartStore。idmutation。storeIdcartonlyavailablewithmutation。typepatchobjectmutation。payloadpatchobjectpassedtocartStore。patch()persistthewholestatetothelocalstoragewheneveritchangeslocalStorage。setItem(cart,JSON。stringify(state))}) 通过localStorage还可以对值进行一个储存,避免被刷新。 对整个piniastate进行监听的话,使用如下:watch(pinia。state,(state){persistthewholestatetothelocalstoragewheneveritchangeslocalStorage。setItem(piniaState,JSON。stringify(state))},{deep:true})Getters Pinia中的Getters作用与Vuex中的Getters相同,但使用略有差异。 Pinia中的Getters直接在Store上读取,形似Store。xx,就和一般的属性读取一样。Getters的基本使用 Getter第一个参数是state,是当前的状态,也可以使用this。xx获取状态。 Getter中也可以访问其他的Getter,或者是其他的Store。 例子:修改store。jsimport{defineStore}frompinia;import{otherState}fromstoreotherState。js;exportconstuseStoredefineStore({id:myGlobalState,state:()({count:2}),getters:{一个基本的Getter:计算count的平方使用参数countPow2(state){returnstate。count2;},使用thiscountPow2(){returnthis。count2;},简单的Getter直接使用箭头函数countPow2:statestate。count2获取其它Getter,直接通过thiscountPow2Getter(){returnthis。countPow2;}使用其它StoreotherStoreCount(state){这里是其他的Store,调用获取Store,就和在setup中一样constotherStoreuseOtherStore();returnstate。count;},}});otherState。jsimport{defineStore}frompinia;exportconstuseStoredefineStore({id:otherState,state:()({count:5}),});actions Pinia没有Mutations,统一在actions中操作state,通过this。xx访问相应状态 虽然可以直接操作Store,但还是推荐在actions中操作,保证状态不被意外改变 action和普通的函数一样 action同样可以像Getter一样访问其他的Store,同上方式使用其它Storestore。jsexportconstuseStore({state:()({count:2,。。。})。。。actinos:{countPlusOne(){this。count;},countPlus(num){this。countnum;}}})如何实现一个? 针对这个pinia的使用,前面讲了这么多api的使用,这些也都是在官网中有介绍的,下面在项目中实际来用下这个库 遇到的问题使用前必须要先注册vuecompositionapi,不然在vue2中不能使用importVueCompositionAPIfromvuecompositionapi;import{createPinia}frompinia;Vue。use(VueCompositionAPI);这里注意:使用之前必选要先注册VueCompositionAPIconstpiniacreatePinia();