vue3 组合式pinia的使用 案例

2023-12-21 17:59:40

需求:用户登录时,结合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的值

文章来源:https://blog.csdn.net/qq_44603011/article/details/135135484
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。