一、pinia简介
Pinia 是一个专门为 Vue.js 应用程序设计的状态管理库。它的设计理念是简化状态管理过程,提供一种清晰、可维护的方式来管理应用程序中的数据。
二、安装与创建
1.你可以通过 npm 或者 yarn 来安装 Pinia:
npm install pinia
# 或者
yarn add pinia
2.创建 Pinia 环境
首先,在你的应用程序中创建一个 Pinia 实例:
import {createApp} from 'vue'
import App from './App.vue'
// 第一步:引入pinia
import {createPinia} from 'pinia'const app = createApp(App)
// 第二步:创建pinia
const pinia = createPinia()
// 第三步:安装pinia
app.use(pinia)
app.mount('#app')
三、定义 Store
接下来,新建 Store目录新建store.ts文件,用于存储和管理应用程序的状态数据:
// 引入defineStore用于创建store
import {defineStore} from 'pinia'
// 定义并暴露一个store
export const useMyStore = defineStore('count',{// 动作actions:{},// 状态state(){return {sum:2}},// 计算getters:{}
})
四、使用 Store
在组件中使用 Store:
<template><div><div v-for="item in data" :key="item.id">{{ item.name }}</div><button @click="fetchData">加载数据</button></div>
</template><script setup>
import { useMyStore } from '@/store';const myStore = useMyStore();const data = myStore.data;
const fetchData = myStore.fetchData;
</script>
五、修改数据
有三种方式可以修改 Store 中的数据:
1.直接修改 State
myStore.data = ['新内容'];
2.批量修改Mutation
myStore.$patch({ data: ['新内容']});
3.使用 action(action中可以编写一些业务逻辑)
import { defineStore } from 'pinia';export const useMyStore = defineStore('myStore', {state: () => ({data: [],}),actions: {async fetchData() {// 模拟从服务器获取数据的异步操作const response = await fetch('https://api.example.com/data');const newData = await response.json();// 提交 Mutation 来修改状态this.$patch({ data: newData });},},
});
⭐组件中调用action
即可
import { useMyStore } from '@/store/store';
// 使用MyStore
const myStore = useMyStore();
// 调用对应action
const fetchData = myStore.fetchData;
六、使用 storeToRefs
可以通过 storeToRefs 将 Store 中的状态数据转换成响应式的 ref:
import { storeToRefs } from 'pinia';
import { useMyStore } from '@/store/store';// 使用 useMyStore 获取 Store 实例
const myStore = useMyStore();// 使用 storeToRefs 将 Store 中的状态数据转换成响应式的 ref
const { data } = storeToRefs(myStore);
- 注意:
pinia
提供的storeToRefs
只会将数据做转换,而Vue
的toRefs
会转换store
中数据。
七、使用 Getters
可以通过定义 Getters 来计算 Store 中的衍生数据:
import { defineStore } from 'pinia';export const useMyStore = defineStore('myStore', {state: () => ({data: [],}),getters: {itemCount() {return this.data.length;},},
});
在组件中使用 Getters:
<template><div>{{ itemCount }}</div>
</template><script setup>
import { useMyStore } from '@/store';const myStore = useMyStore();
const itemCount = myStore.itemCount;
</script>
八、使用 $subscribe
可以使用 $subscribe 方法侦听 Store 中的变化:
const unsubscribe = myStore.$subscribe((mutation) => {console.log('State changed:', mutation);
});// 取消订阅
unsubscribe();
九、Store 组合式写法
可以通过组合多个 Store 来实现更复杂的状态管理:
import { defineStore } from 'pinia';
import { useUserStore } from './userStore';
import { useProductStore } from './productStore';export const useCombinedStore = defineStore({// 省略其他部分setup() {const userStore = useUserStore();const productStore = useProductStore();return {user: userStore,product: productStore,};},
});