这里给大家分享我在网上学习总结出来的一些知识,希望对大家有所帮助
pinia
介绍
vue新一代状态管理库,相当于vuex
特性
1.像定义components一样定义store 2.支持ts 3.去除mutations,只有state,getters,actions(支持同步异步) 4.轻量级(1kb) 5.vuex是要有主入口进行统一导入,pinia可以分模块导入
pina简单使用
1.导入path
项目全局安装 @type/node npm install @types/node --save-dev
2.config设置@指标
3.tsconfig.json设置@指标
4.导入pinia
项目全局安装 pinia npm install pinia --save-dev
5.全局导入pinia
6.store内容设置案例
内容:
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调用方法展示
<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>