Skip to content

配置 pinia 添加持久化

安装

bash
pnpm add pinia@2.0.36 pinia-plugin-persistedstate@3.2.1 -S

根目录下面新建 store 文件夹

里面新建 index.js

js
import { createPinia } from "pinia";
import { createPersistedState } from "pinia-plugin-persistedstate"; // 数据持久化

const store = createPinia();
store.use(
  createPersistedState({
    storage: {
      getItem: uni.getStorageSync,
      setItem: uni.setStorageSync,
    },
  })
);

export default store;

// 模块统一导出count.js
// export * from './user'
export * from "./count";

文件夹里面新建 count.js

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

export const useCountStore = defineStore(
  "countnum",
  () => {
    const countnumInfo = ref(0);

    const setCountnumInfo = (val) => {
      countnumInfo.value = val;
    };

    const clearCountnumInfo = () => {
      countnumInfo.value = 0;
    };
    return {
      countnumInfo,
      setCountnumInfo,
      clearCountnumInfo,
    };
  },
  {
    persist: true,
  }
);

main.js 导入

js
import { createSSRApp } from "vue";
import App from "./App.vue";
import "virtual:uno.css";
import store from "./store";
export function createApp() {
  const app = createSSRApp(App);
  app.use(store);
  return {
    app,
  };
}

使用

html
<template>
  <view
    class="w200rpx h100rpx bg-red-500 text-center text-white text-center line-height-100rpx"
    @click="createadd"
  >
    自定义按钮
  </view>
  <view text-green>{{ store.countnumInfo }}</view>
  <view @click="delall">点击删除</view>
</template>

<script setup>
  import { useCountStore } from "@/store";
  const store = useCountStore();
  const createadd = () => {
    store.setCountnumInfo(15);
  };
  const delall = () => {
    store.clearCountnumInfo();
  };
</script>

<style scoped></style>