前言:
好用的状态管理器,vue3中出来的pinia,相比较vuex来说,更加轻便,使用也更方便。
官方文档:点我
github地址:点我
pinia与vuex相比较优点:
- pinia 是轻量级状态管理工具,大小只有1KB.
- pinia 模块化设计,方便拆分。
- pinia 没有 mutations,直接在 actions 中操作 state
- pinia 支持多个 store。
使用步骤:
1、安装 npm/cnpm/pnpm/yarn 都可以,装上下面插件
pinia
2、main.js中配置
const pinia = createPinia();const app = createApp(App);
app.use(pinia);
3、创建stores 文件夹,
1)官方案例1:
新建一个counter.ts
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', {state: () => {return { count: 0 }},// 也可以定义为// state: () => ({ count: 0 })actions: {increment() {this.count++},},
})
调用的vue
import { useCounterStore } from '@/stores/counter'export default {setup() {const counter = useCounterStore()counter.count++// 带自动补全 ✨counter.$patch({ count: counter.count + 1 })// 或使用 action 代替counter.increment()},
}
2)官方案例2:
定义ts
export const useStore = defineStore('main', {state: () => ({counter: 1,}),actions: {increment() {this.counter++}},getters: {// 类型是自动推断的,因为我们没有使用 `this`doubleCount: (state) => state.counter * 2,/*** 返回计数器值乘以二加一。** @returns {number} 返回类型必须明确设置*/doubleCountPlusOne(): number {// 自动完成 ✨return this.doubleCount + 1},},})
页面使用
<template><p>Double count is {{ store.doubleCount }}</p>
</template><script setup>const store = useStore()const a = store.counterstore.increment()
</script>
3)个人使用:
新建 useChatStore.ts
import {ref} from 'vue';
import {acceptHMRUpdate, defineStore} from 'pinia';export const useChatStore = defineStore('chat', () => {// 定义变量const conversations = ref([]);// 定义方法const getConversations = async (page = 1, search = '', type = '') => {//可以做任何操作};return {conversations ,getConversations };})if (import.meta.hot) {import.meta.hot.accept(acceptHMRUpdate(useChatStore, import.meta.hot));
}
页面调用:
template{{chatStore.conversations }} //拿到数据了<script lang="ts" setup>import { useChatStore } from '/@/stores/useChatStore';const chatStore = useChatStore();//调用定义的方法chatStore.getConversations()
额外的插件:解决刷新数据丢失问题
pinia-plugin-persist
1、安装 npm/cnpm/pnpm/yarn 都可以,装上下面插件
pinia-plugin-persist
2、main.js中配置
import { createPinia} from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist' //++++
const store = createPinia()
store.use(piniaPluginPersist) //++++
3、相应的ts文件中
import { defineStore } from "pinia";
export const useStore= defineStore({state: () => ({active: '111',}),getters: {},// 开启数据缓存 若 需要state 中的变量页面刷新数据缓存 需要调用 actions 中的方法actions: {setActive( active ){this.active = active},},persist: {enabled: true, // 开启数据缓存 +++++++}
});
4、页面上
import { useActiveStore } from '/@/stores/useChatStore' // 引用 pinia 数据
const store = useActiveStore() // 定义 store 接收
store.setActive(222)