当前位置:首页 > VUE

vue实现后台登录

2026-02-20 04:18:50VUE

Vue 实现后台登录功能

创建登录组件

src/views 目录下创建 Login.vue 文件,包含表单、输入框和提交按钮。表单需绑定 v-model 实现双向数据绑定。

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

<script>
export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    handleLogin() {
      // 登录逻辑
    }
  }
}
</script>

配置路由

src/router/index.js 中配置登录页路由,设置为公开路由(无需鉴权)。

vue实现后台登录

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  }
]

实现登录请求

通过 Axios 发送登录请求到后端 API,处理响应并存储 token。

methods: {
  async handleLogin() {
    try {
      const response = await axios.post('/api/login', this.form)
      localStorage.setItem('token', response.data.token)
      this.$router.push('/dashboard')
    } catch (error) {
      alert('登录失败')
    }
  }
}

路由守卫

在路由配置中添加全局前置守卫,检查用户是否已登录。

vue实现后台登录

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

状态管理(可选)

使用 Vuex 集中管理用户登录状态和 token。

const store = new Vuex.Store({
  state: {
    token: null
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    }
  }
})

样式优化

添加基础样式增强用户体验,例如错误提示和加载状态。

.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
.error-message {
  color: red;
}

标签: 后台vue
分享给朋友:

相关文章

vue实现多级表头

vue实现多级表头

Vue 实现多级表头的方法 使用 el-table 组件 Element UI 的 el-table 组件支持多级表头的实现,通过嵌套 el-table-column 即可完成。 <el-ta…

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交换…

vue实现弹幕

vue实现弹幕

Vue 实现弹幕功能 弹幕功能通常包括动态生成、滚动显示、颜色和速度随机化等特性。以下是基于 Vue 3 的实现方法。 核心思路 使用 CSS 动画控制弹幕从右向左滚动。 动态生成弹幕数据,随机设置…

vue实现menu

vue实现menu

Vue 实现 Menu 的方法 使用 Element UI 的 Menu 组件 Element UI 提供了现成的 Menu 组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用…

vue实现表单

vue实现表单

Vue 表单实现方法 双向数据绑定 使用 v-model 指令实现表单元素与数据的双向绑定。适用于 input、textarea、select 等元素。 <template> <…

vue实现分站

vue实现分站

Vue 实现分站的方案 在 Vue 中实现分站功能通常涉及路由配置、环境变量管理和动态加载资源。以下是几种常见的实现方式: 基于路由的分站实现 通过 Vue Router 配置多路由,区分不同站点的…