FrontierVue官方推荐的状态管理库是Vuex,那为什么最近Pinia火了呢?主要原因是Vue3推出的时候,Vuex并没有很好的支持Vue3的组合API,也就是这个时候出现了Pinia。最重要的是Pinia不仅支持Vue3,还支持Vue2,太棒了,最新的Vuex5的特性还是参考Pinia教程官网:https://pinia.vuejs.org/github地址:https://github.com/vuejs/pinia1,安装npminstallpinia-S2,vue中引入//Vue3中引入usingimport{createPinia}from'pinia'app.use(createPinia())//引入Vue2usingimport{createPinia,PiniaVuePlugin}from'pinia'Vue.use(PiniaVuePlugin)constpinia=createPinia()newVue({el:'#app',//其他配置项pinia,})3.基本使用//definestore//stores/counter.jsimport{defineStore}from'pinia'exportconstuseCounterStore=defineStore('counter',{//状态值定义state:()=>{return{count:0}},//state更改方法定义操作:{increment(){this.count++},},})//在组件中使用//importstateimport{useCounterStore}from'@/stores/counter'exportdefault{setup(){//初始化存储实例constcounter=useCounterStore()//状态更新counter.count++//或调用方法更新counter.increment()},}4.你也可以像vuex一样使用constuseCounterStore=defineStore('counter',{//statevaluestate:()=>({count:0}),//gettervaluegetters:{double:(state)=>state.count*2,},//actions方法//注意pinia中没有突变动作:{increment(){this.count++}}})//定义另一个storeconstuseUserStore=defineStore('user',{//...})exportdefault{//在computed中引入使用state中的值computed:{...mapStores(useCounterStore,useUserStore)...mapState(useCounterStore,['count','double']),},//在methods中使用action方法:{...mapActions(useCounterStore,['increment']),},}好了,Pinia的入门教程到此结束。语法更简洁?
