当前位置:首页 > VUE

vue 实现简单登陆

2026-03-06 16:55:03VUE

Vue 实现简单登录功能

创建 Vue 项目

使用 Vue CLI 创建一个新项目:

vue create login-demo

安装必要依赖

安装 axios 用于 HTTP 请求:

npm install axios

创建登录组件

src/components 目录下创建 Login.vue 文件:

vue 实现简单登陆

<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="username">用户名</label>
        <input
          type="text"
          id="username"
          v-model="username"
          required
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input
          type="password"
          id="password"
          v-model="password"
          required
        />
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    async handleSubmit() {
      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) {
        alert('登录失败');
      }
    },
  },
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
.form-group {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}
</style>

配置路由

src/router/index.js 中配置路由:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '../components/Login.vue';
import Dashboard from '../components/Dashboard.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true },
  },
];

const router = new VueRouter({
  routes,
});

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

export default router;

创建模拟 API

src/main.js 中模拟 API 请求:

vue 实现简单登陆

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import axios from 'axios';

axios.interceptors.request.use(config => {
  if (config.url === '/api/login') {
    return new Promise(resolve => {
      setTimeout(() => {
        if (
          config.data.username === 'admin' &&
          config.data.password === '123456'
        ) {
          resolve({
            data: { token: 'fake-jwt-token' },
          });
        } else {
          resolve({
            data: { error: 'Invalid credentials' },
          });
        }
      }, 500);
    });
  }
  return config;
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App),
}).$mount('#app');

创建 Dashboard 组件

src/components 目录下创建 Dashboard.vue 文件:

<template>
  <div>
    <h2>欢迎来到仪表盘</h2>
    <button @click="handleLogout">退出登录</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleLogout() {
      localStorage.removeItem('token');
      this.$router.push('/login');
    },
  },
};
</script>

运行项目

启动开发服务器:

npm run serve

访问 http://localhost:8080/login 测试登录功能,使用用户名 admin 和密码 123456 进行测试。

这个实现包含了基本的登录表单、路由守卫、本地存储 token 和简单的 API 模拟。可以根据实际需求进一步扩展和完善功能。

标签: 简单vue
分享给朋友:

相关文章

vue怎么实现选中删除

vue怎么实现选中删除

实现选中删除功能的方法 在Vue中实现选中删除功能通常涉及以下几个关键步骤: 数据绑定与选中状态管理 使用v-model或v-for指令绑定列表数据,结合复选框或单选按钮实现选中状态管理。例如:…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue实现tag

vue实现tag

Vue 实现标签(Tag)功能 在 Vue 中实现标签(Tag)功能可以通过多种方式完成,以下是一些常见的方法和实现步骤: 使用动态组件和 v-for 通过 v-for 指令动态渲染标签列表,结合样…

vue实现建模

vue实现建模

Vue 实现建模的方法 在 Vue 中实现建模通常涉及数据绑定、组件化和状态管理。以下是几种常见的方法: 数据驱动建模 Vue 的核心是数据驱动视图。通过定义数据模型,Vue 会自动更新 DOM。例…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…