Vue3 uniapp pinia持久化存储

73 阅读1分钟

一、安装插件

// npm install pinia-plugin-persistedstate@3.2.0

二、main.js导入使用插件

import * as Pinia from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

export function createApp() {
	const app = createSSRApp(App)
	const pinia = Pinia.createPinia()
	pinia.use(piniaPluginPersistedstate)
	app.use(pinia)
	return {
		app,
		pinia
	}
}

三、封装useConfigStore.js

import {
	defineStore
} from 'pinia'

import {
	ref,
	reactive
} from 'vue'

export default defineStore('useConfig', () => {
	const baseUrl = ref('https://xxxxxx')
	const openId = ref('')
	return {
		wxBaseUrl,
		jhBaseUrl,
		openId
	}
}, {
	persist: {
		// 存储的键名
		key: 'config_store',
		// 适配uniapp多端存储
		storage: {
			getItem: (key) => uni.getStorageSync(key),
			setItem: (key, value) => uni.setStorageSync(key, value),
			removeItem: (key) => uni.removeStorageSync(key)
		},
		// 指定需要持久化的字段(默认全部持久化)
		// paths: ['openId', 'mobile']
	}
})

四、页面使用

import useConfigStore from '/store/useConfig.js'
import useUserInfoStore from '/store/useUserInfo.js'
import {
  storeToRefs
} from 'pinia'

const {
  wxBaseUrl,
  openId
} = storeToRefs(useConfigStore())
const {
  mobile,
  userInfo
} = storeToRefs(useUserInfoStore())

function getWxOpenid() {
  uni.login({
    success: async resCode => {
      uni.request({
        url: wxBaseUrl.value + `/wx/baseInfo/getWxOpenId`,
        data: {
          code: resCode.code
        },
        success: res => {
          if (res.statusCode === 200 && res.data.code === 200) {
            // store赋值
            openId.value = res.data.data.openid
          }
        }
      })
    }
  })
}