feat(ui): make auth state reactive and close avatar menu

This commit is contained in:
Tim
2025-07-05 14:23:47 +08:00
parent 10e03a0aa8
commit ffeadc9cda
2 changed files with 44 additions and 9 deletions

View File

@@ -32,7 +32,8 @@
</template>
<script>
import { isLogin, clearToken, fetchCurrentUser } from '../utils/auth'
import { authState, clearToken, fetchCurrentUser } from '../utils/auth'
import { watch } from 'vue'
export default {
name: 'HeaderComponent',
@@ -50,16 +51,41 @@ export default {
},
computed: {
isLogin() {
return isLogin()
return authState.loggedIn
}
},
async mounted() {
if (this.isLogin) {
const user = await fetchCurrentUser()
if (user && user.avatar) {
this.avatar = user.avatar
const updateAvatar = async () => {
if (authState.loggedIn) {
const user = await fetchCurrentUser()
if (user && user.avatar) {
this.avatar = user.avatar
}
} else {
this.avatar = 'https://picsum.photos/40'
}
}
await updateAvatar()
watch(() => authState.loggedIn, async () => {
await updateAvatar()
})
watch(() => this.$route.fullPath, () => {
this.dropdownVisible = false
})
this.onClickOutside = (e) => {
if (!this.$el.contains(e.target)) {
this.dropdownVisible = false
}
}
document.addEventListener('click', this.onClickOutside)
},
beforeUnmount() {
document.removeEventListener('click', this.onClickOutside)
},
methods: {

View File

@@ -1,17 +1,26 @@
import { API_BASE_URL } from '../main'
import { reactive } from 'vue'
const TOKEN_KEY = 'token'
export const authState = reactive({
loggedIn: false
})
authState.loggedIn = localStorage.getItem(TOKEN_KEY) !== null && localStorage.getItem(TOKEN_KEY) !== ''
export function getToken() {
return localStorage.getItem(TOKEN_KEY)
}
export function setToken(token) {
localStorage.setItem(TOKEN_KEY, token)
authState.loggedIn = true
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY)
authState.loggedIn = false
}
export async function fetchCurrentUser() {
@@ -29,9 +38,7 @@ export async function fetchCurrentUser() {
}
export function isLogin() {
const token = getToken()
console.log('token', token)
return token !== null && token !== ''
return authState.loggedIn
}
export async function checkToken() {
@@ -41,8 +48,10 @@ export async function checkToken() {
const res = await fetch(`${API_BASE_URL}/api/auth/check`, {
headers: { Authorization: `Bearer ${token}` }
})
authState.loggedIn = res.ok
return res.ok
} catch (e) {
authState.loggedIn = false
return false
}
}