Vite+TS项目:论如何便捷的使用pinia
这里给大家分享我在网上学习总结出来的一些知识,希望对大家有所帮助
pinia
介绍
1 | vue新一代状态管理库,相当于vuex |
特性
1 2 3 4 5 6 7 8 9 | 1.像定义components一样定义store 2.支持ts 3.去除mutations,只有state,getters,actions(支持同步异步) 4.轻量级(1kb) 5.vuex是要有主入口进行统一导入,pinia可以分模块导入 |
pina简单使用
1.导入path
1 2 3 | 项目全局安装 @type/node npm install @types/node --save-dev |
2.config设置@指标
3.tsconfig.json设置@指标
4.导入pinia
1 2 3 | 项目全局安装 pinia npm install pinia --save-dev |
5.全局导入pinia
6.store内容设置案例
内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { defineStore } from 'pinia' export default defineStore( 'myGlobalState' , { state: () => { return { count: 1, message: 'Hello world' , phone: 13811111199 } }, actions:{ countAdd(){ this .count++ } }, getters:{ countSum(state){ return state.count*2 } } }) |
7.demo调用方法展示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <script setup lang= "ts" > import useCommonStore from '@/store/index' import {storeToRefs} from "pinia" ; const store = useCommonStore() const data = storeToRefs(store) // 常规方法修改内容 const storeAdd = ()=>{ data.count.value++ } // $patch修改内容 const storeAddOne = ()=>{ store.$patch({ count:store.count+1 }) } // $patch修改内容,内带对象 const storeAddTwo = ()=>{ store.$patch((state)=>{ state.count++ }) } // $state修改整体内容 const storeRest = ()=>{ store.$state = { count: 1, message: 'Hello world' , phone: 13811111199 } } // $reset重置为初始内容 const storeRestOne = ()=>{ store.$reset() } // $subscribe监听整个仓库变化 store.$subscribe((mutation,store)=>{ console.log( "mutation" ,mutation) console.log( "store" ,store) }) </script> <template> <div class = "box" > <h2> {{store.count}} getters获取值{{store.countSum}} <el-button @click= "storeAdd" type= "primary" >添加一</el-button> <el-button @click= "storeAddOne" type= "primary" >添加二</el-button> <el-button @click= "storeAddTwo" type= "primary" >添加三</el-button> <el-button @click= "storeRest" type= "primary" >重置一</el-button> <el-button @click= "storeRestOne" type= "primary" >重置二</el-button> <el-button @click= "store.countAdd" type= "primary" >actions调用</el-button> </h2> </div> </template> <style scoped lang= "stylus" > .box text-align center line-height 150px </style> |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步