uniapp开发中使用pinia进行持久化存储Storage

126 阅读1分钟

1.下载pinia

npm install pinia

image.png

2.使用pinia

2.1创建pinia的存放文件夹

在src下面创建一个store文件夹 名字可以自己定义

image.png

作用
index.ts----对外导出一个pinia的实例  这个实例会被Vue.use()的
module是管理不同模块的pinia

2.2index.ts创建pinia

import {createPinia} from "pinia"
import persist from "pinia-plugin-persistedstate"
//实例化一个pinia
const Pinia = createPinia()
//persist为了兼容本地存储
Pinia.use(persist)

//导出给main中的Vue
export default Pinia

3. 挂载Pinia

import { createSSRApp } from 'vue'
//导入Pinia  会默认寻找index.ts
import Pinia from './store'

import App from './App.vue'
export function createApp() {
  const app = createSSRApp(App)
    //挂载pinia
  app.use(Pinia)
  return {
    app,
  }
}

4.完善pinia的功能 user.ts

import { defineStore } from "pinia";
import { ref } from "vue";

export const UseUserStore = defineStore(
  'user',
  () => {
    const profile = ref<any>()
    const setProfile = (val: any) => {
      profile.value = val
    }
    const clearProfile = () => {
      profile.value = undefined
    }
    return {
      profile,
      setProfile,
      clearProfile,
    }
  },
  {
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync('key')
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
      },
    },
  },
)

4.1把这统一使用导出

    import {createPinia} from "pinia"
    import persist from "pinia-plugin-persistedstate"
    const Pinia = createPinia()
    Pinia.use(persist)

    export default Pinia

    export * from "./module/user"

5使用这个UseUserStore

进入要使用的页面 例如我的 或是首页

<script setup lang="ts">
//引入UseUserStore
import { UseUserStore } from '@/store'
//实例
const userStore = UseUserStore()
</script>

<template>
  <view>
    存储信息:{{ userStore.profile }}
    //使用实例的方法
    <button type="primary" @click="userStore.setProfile({ name: '李华' })">设置信息 Loading</button>
    <button type="primary" @click="userStore.clearProfile()">清除信息 Loading</button>
  </view>
</template>

<style lang="scss">
//
</style>

6.实现本地存储展示

image.png

image.png

image.png 希望对你有所帮助