|
@@ -43,3 +43,84 @@ export const authState = {
|
|
|
logged: ref<boolean>(isLoggedIn()),
|
|
logged: ref<boolean>(isLoggedIn()),
|
|
|
role: ref<number | null>(getRole())
|
|
role: ref<number | null>(getRole())
|
|
|
}
|
|
}
|
|
|
|
|
+
|
|
|
|
|
+export type LogoutOptions = {
|
|
|
|
|
+ /** 是否先显示确认弹窗,默认 true */
|
|
|
|
|
+ confirm?: boolean
|
|
|
|
|
+ /** 注销后跳转的页面(默认回首页) */
|
|
|
|
|
+ redirectUrl?: string
|
|
|
|
|
+ /** 注销后是否显示 Toast(默认 true) */
|
|
|
|
|
+ showToast?: boolean
|
|
|
|
|
+ /** 注销后回调(可用于清理组件本地状态) */
|
|
|
|
|
+ after?: () => void
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+export async function logout(options: LogoutOptions = {}): Promise<boolean> {
|
|
|
|
|
+ const { confirm = true, redirectUrl = '/pages/public/index/index', showToast = true, after } = options
|
|
|
|
|
+
|
|
|
|
|
+ const doLogout = () => {
|
|
|
|
|
+ try {
|
|
|
|
|
+ // 清理常见的本地存储项
|
|
|
|
|
+ uni.removeStorageSync(tokenKey)
|
|
|
|
|
+ uni.removeStorageSync(roleKey)
|
|
|
|
|
+ try {
|
|
|
|
|
+ uni.removeStorageSync('user_info')
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ // ignore
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (err) {
|
|
|
|
|
+ console.error('logout: removeStorageSync error', err)
|
|
|
|
|
+ }
|
|
|
|
|
+ // 更新 reactives
|
|
|
|
|
+ try {
|
|
|
|
|
+ authState.logged.value = false
|
|
|
|
|
+ authState.role.value = null
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ // ignore
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ if (showToast) uni.showToast({ title: '已退出登录', icon: 'none' })
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ // ignore
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (typeof after === 'function') {
|
|
|
|
|
+ try {
|
|
|
|
|
+ after()
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ console.error('logout: after callback error', e)
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ // 使用 reLaunch 清空页面栈
|
|
|
|
|
+ if (redirectUrl) {
|
|
|
|
|
+ uni.reLaunch({ url: redirectUrl })
|
|
|
|
|
+ }
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ console.error('logout: reLaunch error', e)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return true
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if (confirm) {
|
|
|
|
|
+ return new Promise((resolve) => {
|
|
|
|
|
+ uni.showModal({
|
|
|
|
|
+ title: '提示',
|
|
|
|
|
+ content: '确定要退出登录吗?',
|
|
|
|
|
+ success: (res) => {
|
|
|
|
|
+ if (res.confirm) {
|
|
|
|
|
+ doLogout()
|
|
|
|
|
+ resolve(true)
|
|
|
|
|
+ return
|
|
|
|
|
+ }
|
|
|
|
|
+ resolve(false)
|
|
|
|
|
+ }
|
|
|
|
|
+ })
|
|
|
|
|
+ })
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return Promise.resolve(doLogout())
|
|
|
|
|
+}
|