vue3-登录小案例(借助ElementPlus+axios)

1.创建一个vue3的项目。

复制代码
npm create vue@latest

2.引入Elementplus组件库

链接:安装 | Element Plus

复制代码
npm install element-plus --save

在main.js中引入

复制代码
import ElementPlus from "element-plus";

import "element-plus/dist/index.css";

app.use(ElementPlus);

3.开始渲染页面

引入axios

链接:POST 请求 | Axios中文文档 | Axios中文网

引入步骤:

1.导入

复制代码
import axios from "axios";

2.调用axios.post

复制代码
const SubmitEvent = async () => {
  const { data } = await axios.post(
    "https://v5.crmeb.net/api/login",
    {
      account: acc.value,
      password: pwd.value,
    },
    {
      headers: {
        "Content-Type": "application/json",
      },
    }
  );

具体实现代码如下:

复制代码
<template>
  <div>
    <div class="box">
      <br />
      <el-input
        v-model="acc"
        style="width: 240px"
        placeholder="Please input"
        clearable
      />
      <br />
      <br />
      <el-input
        v-model="pwd"
        style="width: 240px"
        type="password"
        placeholder="Please input password"
        show-password
      />
      <br /><br />
      <el-button @click="SubmitEvent" type="primary" style="width: 240px"
        >login</el-button
      >
    </div>
  </div>
</template>

<style>
.box {
  width: 300px;
  height: 300px;
  background-color: antiquewhite;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";
const router = useRouter();
const acc = ref("");
const pwd = ref("");
const SubmitEvent = async () => {
  const { data } = await axios.post(
    "https://v5.crmeb.net/api/login",
    {
      account: acc.value,
      password: pwd.value,
    },
    {
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  if (data.status == 200) {
    ElMessage({
      message: "登录成功",
      type: "success",
    });
    // 保存到本地
    localStorage.setItem("token", data.data.token);
    // 跳转
    router.replace({
      name: "about",
    });
  } else {
    ElMessage.error("登录失败");
    acc.value = "";
    pwd.value = "";
  }
};
</script>

效果图:

输入信息错误会清空数据并提示登录失败:

输入信息正确会跳转到另外一个页面并提示登录成功:

相关推荐
Carsene1 分钟前
开源项目文档架构设计:Git Submodule 实现文档与代码的优雅分离
前端·后端
Z思学4 分钟前
promise 有几种状态 async/await 和promise 有什么关系
前端
han_6 分钟前
JavaScript设计模式(四):发布-订阅模式实现与应用
前端·javascript·设计模式
27669582928 分钟前
租车帮(悟空)订单查询算法分析
java·服务器·前端·悟空·悟空app·租车帮·租车帮逆向
用户3266584037418 分钟前
如何初始化 TypeScript + Node.js 项目
javascript
__雨夜星辰__20 分钟前
TypeScript 入门学习笔记(面向对象 + 常用设计模式)
前端·学习·typescript
晚霞的不甘35 分钟前
HarmonyOS ArkTS 进阶实战:深入理解边距、边框与嵌套布局
前端·计算机视觉·华为·智能手机·harmonyos
_野猪佩奇_牛马版35 分钟前
ReACT Agent 开发知识点总结
前端
牛奶1 小时前
你发送的消息,微信到底怎么送到的?
前端·websocket·http
酉鬼女又兒1 小时前
零基础快速入门前端DOM 元素获取方法详解:从代码到实践(可用于备赛蓝桥杯Web应用开发)
前端·javascript·职场和发展·蓝桥杯·js