需求:用户登录时,结合session实现永久化存贮个人信息
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { logOn } from '@/service'
// sessionStorage的封装
import { SET_USER_TOKEN, STORAGE_GET, STORAGE_SET } from '@/utils/sessionStorage'
import { ILogOn } from '@/service/interface'
import router from '@/router'
export default defineStore('customer', () => {
const businessIf: any = ref({})
// 用户登录的信息
const businessInfo = computed(() => {
const result = Object.keys(businessIf.value).length ? JSON.stringify(businessIf.value) : STORAGE_GET('customer-info')
if (result) return JSON.parse(result)
return {}
})
const login = async (userForm: ILogOn) => {
// Login
const customerLoginRes = await logOn(userForm)
businessIf.value = customerLoginRes.payload.customer
// 存用户信息
STORAGE_SET('customer-info', JSON.stringify(customerLoginRes.payload.customer))
// 存token
SET_USER_TOKEN(customerLoginRes.payload.accessToken)
// 取新的token
STORAGE_SET('refresh_token', customerLoginRes.payload.refreshToken)
router.push('/')
}
const updateBusinessInfoValue = (newValue: any) => {
businessIf.value = newValue;
}
return { businessInfo, login, businessIf, updateBusinessInfoValue }
})
组件中使用pinia
组件中修改pinia的值