This commit is contained in:
Your Name
2026-07-14 10:00:34 +08:00
parent 01152efce6
commit 99a6ca0a77
59 changed files with 10014 additions and 0 deletions
+47
View File
@@ -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 }
})