Pinia 是一个基于 Vue3 的状态管理库,它提供了简单且强大的方法来管理应用程序的状态。
一、安装 Pinia
npm install pinia
二、注册 Pinia Store
我们需要在应用程序的入口文件中注册 Pinia Store,以便它能够在整个应用程序中使用。
// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
const pinia = createPinia();
app.use(pinia);
app.mount('#app');
三、创建 Pinia Store
接下来,我们需要创建一个 Pinia Store 来管理应用程序的状态。
// index.js
import { createStore } from 'pinia';
export const useCounterStore = createStore('counter',{
state: () => {
return {
count: 0,
}
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
在上面createStore函数中,第一个参数是id,用于区别部分不同的store,当然你也可以将id用枚举方式保存
,避免重复造成不必要的麻烦
//enum/index.ts 用于存储store中的id值
export const enum storeId {
COUNTER = "counter",
}
// store/index.js
import { defineStore } from "pinia";
import { storeId } from "@/enum/index";
export const useCounterStore = defineStore(storeId.COUNTER, {
state: () => {
return {
count: 0
}
},
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
actions中存放我们的逻辑代码,如接口请求等。
四、使用 Pinia Store
获取store中的值,下面这五种方法都可以获取到
<template>
<div>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
{{ Count.count }}
</div>
</template>
<script setup lang="ts">
import { useCounterStore } from "@/store/index";
const Count = useCounterStore();
const increment = () => {
//1
Count.count++;
//2
Count.$patch({
count: Count.count + 1,
});
//3
Count.$patch(() => {
Count.count += 2;
});
//4
Count.increment();
};
const decrement = () => {
Count.count--;
};
</script>
<style scoped lang="scss">
</style>
在上面四种方法可以看出,Pinia简化了操作,获取和设置值更加简单。
但Pinia直接解构值没有响应效果,这需要我们借助它的storeToRefs
方法转为ref模式,如下:
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/store/index";
const Count = useCounterStore();
let { count } = storeToRefs(Count);
const increment = () => {
//5
count.value++;
};
上面只是本人学习pinia后做的简单总结,更多方法请参考pinia官网