Vue+Element的注册功能和登录页面功能实现

https://pan.baidu.com/s/1bkMmMQJKS-5iHwl1kDzizg?pwd=3698

1.首先安装VUE

步骤1:npm create vue (安装插件router选择是,其他选否)

步骤2:cd 项目文件夹名称(上一步创建的,一般默认为vue-project)

步骤3:npm install

步骤4:安装element-plus  npm install element-plus --save

然后修改src/main.js的代码如下:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App).use(router).use(ElementPlus).mount('#app')

步骤5:npm run dev

打开链接,能成功运行,就完成了VUE的安装。

2.在router/index.js中配置首页,代码如下:

import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";

const routes = [
  {
    path: "/",
    name: "HomeView",
    meta: {
      requireAuth: true // 添加该字段,表示进入这个路由是需要登录的
    },
    component: HomeView,
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/sign/login.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("../views/sign/register.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to) => {
  const token = localStorage.getItem("token");
  // 如果访问非登录界面,且户会话信息不存在,代表未登录,则跳转到登录界面
  if (to.meta.requireAuth && !token) {
    return { name: 'Login' }
  }
  return true;
});
export default router;

3.修改App.vue的代码

<template>
  <router-view></router-view>
</template>
<script>
export default {
  name: 'App',
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
html,
body,
div,
ul,
h1,
h2,
h3,
p {
  padding: 0;
  margin: 0;
}
.w100p {
  width: 100%;
}
.txt-r {
  text-align: right;
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

4.在src目录下创建一个views/sign/register.vue文件,添加代码:

<template>
    <div class="page flex-center">
      <div class="sign-box">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <h3 class="title">系统注册</h3>
          <el-form-item label="账号" prop="account">
            <el-input
              v-model="form.account"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="cfpassword">
            <el-input
              v-model="form.cfpassword"
              type="password"
              placeholder="请确认密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" class="w100p" @click="register"
              >注册</el-button
            >
          </el-form-item>
          <div class="txt-r">
            <router-link to="/login">已有账号?去登录</router-link>
          </div>
        </el-form>
      </div>
    </div>
  </template>
  <script>
  export default {
    name: "register",
    data() {
      const validateCfpassword = (rule, value, callback) => {
        if (value !== this.form.cfpassword) {
          callback(new Error("两次密码输入不一致"));
        } else {
          callback();
        }
      };
      return {
        form: {
          account: "",
          password: "",
          cfpassword: "",
        },
        rules: {
          account: [
            { required: true, message: "请输入用户名", trigger: ["change", "blur"] },
            { pattern: /^[a-zA-Z][a-zA-Z0-9_-]{3,31}$/, message: '用户名由英文字母开头的长度3-32位字母、_和-组成', trigger: ["change", "blur"] },
          ],
          password: {
            required: true,
            min: 6,
            message: "请输入至少6个字符的密码",
            trigger: ["change", "blur"],
          },
          cfpassword: [
            {
              required: true,
              message: "请确认密码",
              trigger: ["change", "blur"],
            },
            {
              validator: validateCfpassword,
              trigger: ["change", "blur"],
            },
          ],
        },
      };
    },
    methods: {
      register() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 模拟像后台请求数据
            const post = (params) => {
              // 模拟后台比对数据
              return new Promise((resolve, reject) => {
                const { account, password } = params
                let db_user = localStorage.getItem("db_user");
                if (db_user) {
                  db_user = JSON.parse(db_user);
                } else {
                  db_user = []
                }
                if (!db_user.find((v) => v.account === account)) {
                  db_user.push({ account, password });
                  localStorage.setItem("db_user", JSON.stringify(db_user));
                  resolve ({ msg: '注册成功!'});
                } else {
                  reject({msg: `用户名:${account}已存在!`});
                }
              })
            };
            post(this.form).then((res) => {
              alert(`${res.msg}用户名:${this.form.account},密码: ${this.form.password}` );
              this.$router.push("/");
            }).catch(err => {
              alert(err.msg);
            })
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };
  </script>
  
  <style lang="css">
  @import url(./index.css);
  </style>

5.在src目录下创建一个views/sign/login.vue文件,添加代码:

<template>
    <div class="page flex-center">
      <div class="sign-box">
        <el-form ref="form" :model="form" :rules="rules" label-width="60px">
          <h3 class="title">系统登录</h3>
          <el-form-item label="账号" prop="account">
            <el-input
              v-model="form.account"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" class="w100p" @click="login"
              >登录</el-button
            >
          </el-form-item>
          <div class="txt-r">
            <router-link to="/register">没有账号?去注册</router-link>
          </div>
        </el-form>
      </div>
    </div>
  </template>
  <script>
  export default {
    name: "login",
    data() {
      return {
        form: {
          account: "",
          password: "",
        },
        rules: {
          account: [
            {
              required: true,
              message: "请输入用户名",
              trigger: ["change", "blur"],
            },
            {
              pattern: /^[a-zA-Z][a-zA-Z0-9_-]{3,31}$/,
              message: "用户名由英文字母开头的长度4-32位字母、_和-组成",
              trigger: ["change", "blur"],
            },
          ],
          password: {
            required: true,
            min: 6,
            message: "请输入至少6个字符的密码",
            trigger: ["change", "blur"],
          },
        },
      };
    },
    methods: {
      login() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 模拟后台数据处理
            const post = ((params) => {
              // 模拟后台比对数据
              return new Promise((resolve, reject) => {
                let db_user = localStorage.getItem("db_user");
                if (db_user) {
                  db_user = JSON.parse(db_user);
                }
                const { account, password } = params
                if (db_user.find((v) => v.account === account && v.password === password)) {
                  resolve({msg: '登录成功!', token: Date.now()});
                } else {
                  reject({msg: '用户名或密码错误!'})
                }
              })
            });
            post(this.form).then((res) => {
              alert(`${res.msg}` );
              localStorage.setItem("token", res.token);
              this.$router.push("/");
            }).catch(err => {
              alert(err.msg);
            })
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };
  </script>
  
  <style lang="css">
  @import url(./index.css);
  </style>

6.在src目录下创建一个views/sign/index.css文件,添加代码:

.page {
    height: 100vh;
  }
  a {
    color: blue;
  }
  .sign-box {
    width: 400px;
    background: #fff;
    padding: 30px 30px;
    border-radius: 4px;
    box-shadow: 0 0 25px #cac6c6;
  }
  .title {
    font-size: 20px;
    line-height: 30px;
    margin-bottom: 10px;
    color: #000;
  }
  .flex {
    display: flex;
    justify-content: center;
    align-items: center;
  }

7.修改HomeView.vue文件,代码如下:

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  }
}
</script>

最后在终端运行 npm run dev

以下是一个简单的 Vue.js 使用 Element UI 实现的登录注册页面的代码示例: ```vue <template> <div class="login-register"> <el-form :model="form" ref="form" label-width="80px"> <el-form-item label="用户名" prop="username"> <el-input v-model="form.username"></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="form.password"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="login">登录</el-button> <el-button type="primary" @click="register">注册</el-button> </el-form-item> </el-form> </div> </template> <script> export default { data() { return { form: { username: '', password: '' } }; }, methods: { login() { this.$refs.form.validate(valid => { if (valid) { // 处理登录逻辑 console.log('登录成功'); } else { console.log('请填写正确的用户名和密码'); return false; } }); }, register() { this.$refs.form.validate(valid => { if (valid) { // 处理注册逻辑 console.log('注册成功'); } else { console.log('请填写正确的用户名和密码'); return false; } }); } } }; </script> <style scoped> .login-register { max-width: 400px; margin: 0 auto; padding-top: 100px; } </style> ``` 以上代码使用了 Element UI 的 `el-form` 和 `el-input` 组件来实现登录和注册表单,通过 `v-model` 来绑定表单数据。登录和注册按钮分别绑定 `login` 和 `register` 方法,通过 `this.$refs.form.validate` 来进行表单验证,然后处理相应的逻辑。你可以根据实际需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值