更新
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import api from '@/api'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const token = ref(localStorage.getItem('token') || '')
|
||||
const user = ref(null)
|
||||
const initialized = ref(false)
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value && !!user.value)
|
||||
|
||||
async function init() {
|
||||
if (token.value) {
|
||||
try {
|
||||
const res = await api.get('/auth/me')
|
||||
user.value = res.data.data
|
||||
} catch {
|
||||
logout()
|
||||
}
|
||||
}
|
||||
initialized.value = true
|
||||
}
|
||||
|
||||
async function login(account, password) {
|
||||
const res = await api.post('/auth/login', { account, password })
|
||||
token.value = res.data.data.token
|
||||
user.value = res.data.data.user
|
||||
localStorage.setItem('token', token.value)
|
||||
return res.data
|
||||
}
|
||||
|
||||
async function register(username, email, password) {
|
||||
const res = await api.post('/auth/register', { username, email, password })
|
||||
token.value = res.data.data.token
|
||||
user.value = res.data.data.user
|
||||
localStorage.setItem('token', token.value)
|
||||
return res.data
|
||||
}
|
||||
|
||||
function logout() {
|
||||
token.value = ''
|
||||
user.value = null
|
||||
localStorage.removeItem('token')
|
||||
}
|
||||
|
||||
return { token, user, initialized, isLoggedIn, init, login, register, logout }
|
||||
})
|
||||
Reference in New Issue
Block a user