当前位置:首页 > 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 添加全局前置守卫:

vue实现线上登录

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:

vue实现线上登录

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:

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表格实现教学

vue表格实现教学

Vue 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&…

vue实现页面截屏

vue实现页面截屏

使用html2canvas库实现截屏 html2canvas是一个流行的JavaScript库,可以将DOM元素转换为Canvas图像。在Vue项目中安装html2canvas: npm insta…

vue实现导航切换内容

vue实现导航切换内容

Vue实现导航切换内容的方法 在Vue中实现导航切换内容,可以通过以下方式实现: 使用动态组件 动态组件通过<component :is="currentComponent">实现内容…

vue设计与实现 书

vue设计与实现 书

vue设计与实现 书 《Vue.js设计与实现》是一本深入探讨Vue.js框架内部原理和设计思想的书籍,适合希望深入理解Vue.js的开发者。以下是关于这本书的详细信息: 书籍内容 《Vue…

vue状态管理怎么实现

vue状态管理怎么实现

Vue 状态管理实现方法 使用 Vuex(官方推荐) Vuex 是 Vue 的官方状态管理库,适合中大型应用。 安装 Vuex: npm install vuex --save 创建 Store…

vue实现签约合作弹窗

vue实现签约合作弹窗

实现签约合作弹窗的步骤 使用Vue实现签约合作弹窗可以通过组件化方式完成,结合模态框和表单交互逻辑。以下是具体实现方法: 1. 创建弹窗组件 新建一个Vue组件文件(如SignContractDi…