Pinia
pinia是全局状态管理库,具有一下特点
- 完整的ts支持
- 体积小
- 去除mutations,使用方便
- actions支持同步和异步
- 支持vue3和vue2
安装
npm install pinia
引入注册
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
const store = createPinia()
let app = createApp(App)
app.use(store)
app.mount('#app')
使用
1. 新建文件夹store
2. 新建index.ts
新建store-name.ts
export const enum Names {
Test = 'TEST'
}
import {defineStore} from "pinia";
import {Names} from './store-name.ts'
export const useTestStore = defineStore(Names.TEST,{
state:()=>{
return {
current:1,
name:'熏悟空'
}
},
//computed
getters:{
},
//methods 可以同步或异步更新state
actions:{
setCurrent(num:number){
this.current = num
}
}
})
3. Vue组件中使用
<template>
<div>
pinia: {{Test.current}} -- {{Test.name}}
<button @click="change">change</button>
</div>
</template>
<script setup lang=ts>
import {useTestStore} from "@/store";
const Test = useTestStore();
/**
* 修改state值的方式
* 1, Test.current++
* 2, Test$patch({name:"唐僧"})
* 3. Test.$patch((state) => {state.name="唐僧"})
* 4. Test.$state = {current:2000,name:"唐僧"}
* 5. 通过actions修改state
*/
const change = ()=>{
Test.setCurrent(123)
}
</script>
<style scoped>
</style>