当前位置:首页 > VUE

vue登录实现方法

2026-02-19 01:32:36VUE

Vue 登录功能实现方法

前端实现(Vue.js)

创建登录表单组件
使用 Vue 的单文件组件创建登录表单,包含用户名和密码输入框以及提交按钮。通过 v-model 实现双向数据绑定。

<template>
  <div class="login-form">
    <input v-model="username" placeholder="用户名" />
    <input v-model="password" type="password" placeholder="密码" />
    <button @click="handleLogin">登录</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('/api/login', {
          username: this.username,
          password: this.password
        })
        localStorage.setItem('token', response.data.token)
        this.$router.push('/dashboard')
      } catch (error) {
        console.error('登录失败', error)
      }
    }
  }
}
</script>

后端API对接

使用 Axios 发送登录请求
安装 axios 并配置基础 URL 和请求拦截器。

vue登录实现方法

import axios from 'axios'

axios.defaults.baseURL = 'http://your-api-domain.com'
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

路由守卫配置

设置路由守卫保护需要认证的路由
在 Vue Router 中配置全局前置守卫,检查用户是否已登录。

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

状态管理(Vuex)

使用 Vuex 管理用户登录状态
创建 store 模块存储用户信息和登录状态。

vue登录实现方法

const store = new Vuex.Store({
  state: {
    user: null,
    isAuthenticated: false
  },
  mutations: {
    setUser(state, user) {
      state.user = user
      state.isAuthenticated = true
    },
    logout(state) {
      state.user = null
      state.isAuthenticated = false
    }
  },
  actions: {
    login({ commit }, credentials) {
      return axios.post('/api/login', credentials)
        .then(response => {
          commit('setUser', response.data.user)
          localStorage.setItem('token', response.data.token)
        })
    }
  }
})

安全注意事项

实现 JWT 过期处理
在响应拦截器中检查 token 是否过期,若过期则跳转至登录页。

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response.status === 401) {
      store.commit('logout')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

表单验证

添加客户端表单验证
使用 Vuelidate 或自定义验证方法确保输入符合要求。

import { required, minLength } from 'vuelidate/lib/validators'

export default {
  validations: {
    username: { required },
    password: { required, minLength: minLength(6) }
  },
  methods: {
    handleLogin() {
      this.$v.$touch()
      if (!this.$v.$invalid) {
        // 提交表单
      }
    }
  }
}

标签: 方法vue
分享给朋友:

相关文章

vue实现弹窗

vue实现弹窗

Vue 实现弹窗的常见方法 使用组件化方式封装弹窗 创建一个独立的弹窗组件(如 Modal.vue),通过 v-if 或 v-show 控制显示隐藏: <template> <…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue实现modal

vue实现modal

Vue 实现 Modal 弹窗组件 使用 Vue 实现 Modal 弹窗组件可以通过多种方式,包括原生 Vue 组件、第三方库或自定义指令。以下是几种常见方法: 原生 Vue 组件实现 创建一个基础…

vue实现文字

vue实现文字

Vue 中实现文字显示的方法 在 Vue 中实现文字显示可以通过多种方式,包括插值表达式、指令、组件等。以下是几种常见的实现方法: 插值表达式 使用双大括号 {{ }} 进行文本插值,这是 Vue…

通过vue实现

通过vue实现

Vue 实现方法 安装 Vue 确保已安装 Node.js 和 npm,通过以下命令安装 Vue CLI: npm install -g @vue/cli 创建 Vue 项目 使用 Vue CLI…

vue实现vnc

vue实现vnc

Vue 实现 VNC 客户端 在 Vue 项目中实现 VNC 客户端功能,可以通过集成现有的 VNC 客户端库或组件完成。以下是具体实现方法: 安装依赖库 使用 noVNC 或其他 VNC 客户端…