vue3 pinia 状态管理的使用

292 阅读2分钟

安装 pinia

  pnpm install pinia

安装完成后,你可以在项目中开始使用 Pinia

 // @/store/index.ts

import type { App } from "vue";
import { createPinia } from "pinia";

const store = createPinia();

export function setupStore(app: App<Element>) {
  app.use(store);
}

export { store };

在 main.ts 中引入并使用 Pinia

import { setupStore } from "@/store";

setupStore(app)

在项目中使用pinia

  • 定义一个 Store文件夹,用于存放所有的 Store
  @/store/modules/a.ts
   import { defineStore } from 'pinia'
    interface State {
    count: number;
    name:string; 
    }
    export const useAStore  = defineStore('counter', {
    state: ():State=> ({
        count: 0,
        name:"Berry"
    }),
    getters: {
        doubleCount: (state) => state.count * 2,
    },
    actions: {
        increment() {
        this.count++;
        },
    },
    });
  • 在组件中使用 Store
<template>
  <div>
    {{ count }}--{{ name }} --{{ doubleCount }}
    <p>{{ aStore.count }}</p>
    <p>{{ aStore.name }}</p>
    {{ aStore.doubleCount  }}
    {{ ad }}
    <el-button  @click ="hanldeCount" type="primary">Primary</el-button>
    <baseDefineProps :user="user" :isRequired ="isRequired" :minLength = "minLength"></baseDefineProps>
    <base-props  :user="user" :isRequired ="isRequired" :minLength = "minLength"></base-props>
  </div>
</template>

<script setup lang='ts'>
import baseDefineProps from './components/base-defineProps.vue';
import baseProps from './components/base-props.vue';
import { useAStore } from '@/store/test/a'; // 导入 Store
import { storeToRefs  } from 'pinia'; // 导入 storeToRefs

const berlvyStore = useAStore();

// 使用 storeToRefs 解构状态
const { count, name, doubleCount } = storeToRefs(berlvyStore); // 解构状态


const hanldeCount = ()=>{
  aStore.increment()
}
const ad = ref('aa')
const user = ref({
  id: 1,
  name: 'John Doe',
  email: 'john.doe@example.com',
});
const isRequired = ref(true);
const minLength = ref(5);

</script>

<style scoped>
</style>

Pinia的状态保存在localStorage或sessionStorage中,即使页面刷新或关闭后再次打开,状态依然会被恢复。

使用npm或yarn安装pinia-plugin-persistedstate

npm install pinia-plugin-persistedstate --save
# 或者使用 yarn
yarn add pinia-plugin-persistedstate

在pinia 中配置 pinia-plugin-persistedstate

 import type { App } from "vue";
import { createPinia } from "pinia";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; // 引入 pinia-plugin-persistedstate
const store = createPinia();
store.use(piniaPluginPersistedstate); // 配置 pinia-plugin-persistedstate
export function setupStore(app: App<Element>) {
  app.use(store);
}

export { store };

使用pinia-plugin-persistedstate 持久化状态

import { defineStore } from 'pinia'

interface State {
  count: number;
  name:string; 
}
export const useAStore  = defineStore('counter', {
  state: ():State=> ({
    count: 0,
    name:"Berry"
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
  },
  // 在 Store 中启用持久化:在定义具体的 store 时,通过 persist 选项来启用状态持久化功能。可以根据需求设置不同的持久化配置:
  // persist: true, // 启用持久化,默认使用 localStorage 存储
  persist: {
    storage: localStorage, // 持久化到 localStorage 或者 sessionStorage
    key: 'counterkey', // 存储的键名
    paths: ['count,name'], // 要持久化的状态字段,可以是一个数组,也可以是一个函数,用于动态选择要持久化的字段
    //pick: ['count'], // 只持久化 count 字段
    // 其他配置项...

  },
});

在这里插入图片描述