Vue 中登錄功能的簡單實現


登錄

表單驗證用戶名與密碼,發送登錄請求

login() {
  // 數據驗證
  this.$refs.loginFormRef.validate(async valid => {
    // 驗證不通過
    if (!valid) return
    // 數據請求
    const { data: res } = await this.$https.post('login', this.loginForm)
    // 登錄失敗
    if (res.meta.status !== 200) return this.$message.error('登錄失敗!')
    // 登錄成功
    this.$message.success('登錄成功!')
    // 緩存token
    window.sessionStorage.setItem('token', res.data.token)
    // 跳轉主頁面
    this.$router.push('/home')
  })
}

路由與路由守衛

通過導航守衛判斷用戶是否登錄

// 路由配置
const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: login },
    { path: '/home', component: home }
  ]
})

// 掛載路由守衛,驗證token是否已存在
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

退出登錄

刪除token,跳到登錄頁

logout() {
  window.sessionStorage.clear()
  this.$router.push('/login')
}

通過接口獲取數據

通過axios請求攔截器添加token,保證擁有獲取數據的權限

// main.js中,axios請求攔截器
axios.interceptors.request.use(config => {
  // 為請求頭對象添加token驗證的Authorization字段
  config.headers.Authorization = window.sessionStorage.getItem('token')
  return config
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM