auth.js 1.19 KB
import { ref, provide, inject, onMounted } from 'vue'

// 创建认证上下文的key
const authKey = Symbol('auth')

/**
 * 提供认证功能的组合式函数
 */
export function provideAuth() {
  const currentUser = ref(null)
  const loading = ref(true)

  // 初始化时检查本地存储的用户信息
  onMounted(() => {
    const savedUser = localStorage.getItem('currentUser')
    if (savedUser) {
      currentUser.value = JSON.parse(savedUser)
    }
    loading.value = false
  })

  // 登录函数
  const login = (userData) => {
    currentUser.value = userData
    localStorage.setItem('currentUser', JSON.stringify(userData))
    return true
  }

  // 登出函数
  const logout = () => {
    currentUser.value = null
    localStorage.removeItem('currentUser')
  }

  // 提供认证上下文
  provide(authKey, {
    currentUser,
    loading,
    login,
    logout
  })

  return {
    currentUser,
    loading,
    login,
    logout
  }
}

/**
 * 使用认证功能的组合式函数
 * @returns {Object} 认证上下文值
 */
export function useAuth() {
  const auth = inject(authKey)
  if (!auth) {
    throw new Error('useAuth 必须在 provideAuth 的范围内使用')
  }
  return auth
}