当前位置:首页 > VUE

vue实现线上登录

2026-01-16 22:41:18VUE

Vue 实现线上登录

使用 Vue Router 和 Vuex 管理登录状态

安装 Vue Router 和 Vuex 依赖:

npm install vue-router vuex

创建路由配置文件 router/index.js,定义登录路由:

import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

创建 Vuex store 管理登录状态 store/index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    isAuthenticated: false,
    user: null
  },
  mutations: {
    setAuth(state, payload) {
      state.isAuthenticated = payload.isAuthenticated
      state.user = payload.user
    }
  },
  actions: {
    login({ commit }, userData) {
      // 调用登录API
      commit('setAuth', {
        isAuthenticated: true,
        user: userData
      })
    },
    logout({ commit }) {
      commit('setAuth', {
        isAuthenticated: false,
        user: null
      })
    }
  }
})

创建登录组件

创建登录页面组件 views/Login.vue

<template>
  <div class="login">
    <form @submit.prevent="handleSubmit">
      <input v-model="username" type="text" placeholder="用户名">
      <input v-model="password" type="password" placeholder="密码">
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    ...mapActions(['login']),
    async handleSubmit() {
      try {
        await this.login({
          username: this.username,
          password: this.password
        })
        this.$router.push('/')
      } catch (error) {
        console.error('登录失败:', error)
      }
    }
  }
}
</script>

添加路由守卫

修改 router/index.js 添加全局前置守卫:

router.beforeEach((to, from, next) => {
  const isAuthenticated = store.state.isAuthenticated
  if (to.name !== 'Login' && !isAuthenticated) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

实现 API 请求

创建 api/auth.js 处理登录请求:

import axios from 'axios'

export default {
  login(credentials) {
    return axios.post('/api/login', credentials)
  }
}

更新 Vuex action 使用 API:

actions: {
  async login({ commit }, userData) {
    try {
      const response = await authApi.login(userData)
      commit('setAuth', {
        isAuthenticated: true,
        user: response.data.user
      })
    } catch (error) {
      throw new Error('登录失败')
    }
  }
}

处理 Token 存储

安装 js-cookie 存储 token:

npm install js-cookie

更新登录逻辑存储 token:

import Cookies from 'js-cookie'

actions: {
  async login({ commit }, userData) {
    const response = await authApi.login(userData)
    Cookies.set('token', response.data.token)
    commit('setAuth', {
      isAuthenticated: true,
      user: response.data.user
    })
  }
}

添加请求拦截器自动附加 token:

axios.interceptors.request.use(config => {
  const token = Cookies.get('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

实现自动登录

检查本地存储的 token 实现自动登录:

created() {
  const token = Cookies.get('token')
  if (token) {
    this.$store.dispatch('autoLogin', token)
  }
}

添加 autoLogin action:

vue实现线上登录

actions: {
  async autoLogin({ commit }, token) {
    try {
      const response = await authApi.verifyToken(token)
      commit('setAuth', {
        isAuthenticated: true,
        user: response.data.user
      })
    } catch (error) {
      Cookies.remove('token')
    }
  }
}

标签: 线上vue
分享给朋友:

相关文章

vue实现drag

vue实现drag

Vue 实现拖拽功能的方法 在 Vue 中实现拖拽功能可以通过原生 HTML5 的拖拽 API 或第三方库如 vuedraggable 来完成。以下是两种常见方法的实现方式。 使用 HTML5 拖拽…

vue实现开关

vue实现开关

Vue 实现开关组件的方法 使用原生HTML和Vue数据绑定 通过v-model绑定复选框的checked状态,结合CSS样式实现开关效果: <template> <label…

vue实现Pop

vue实现Pop

Vue 实现 Popover 组件的方法 使用 Vue 内置指令 v-show/v-if 和事件监听 通过 Vue 的指令和事件绑定实现基础的 Popover 功能。定义一个布尔值控制 Popover…

vue源码实现

vue源码实现

Vue 源码实现解析 Vue.js 的核心实现可以分为响应式系统、虚拟 DOM、模板编译、组件化等几个关键部分。以下是对这些核心机制的详细解析。 响应式系统 Vue 的响应式系统基于 Object.…

vue 实现穿透

vue 实现穿透

Vue 样式穿透的实现方法 在 Vue 中,样式穿透通常指在带有 scoped 属性的样式块中,强制影响子组件的样式。以下是几种常见的实现方式: 使用 >>> 或 /deep/ 选…

vue实现fragment

vue实现fragment

Vue 实现 Fragment 的方法 在 Vue 中,Fragment 允许组件返回多个根节点而不需要包裹一个额外的 DOM 元素。以下是几种实现方式: 使用 Vue 3 的 <templa…