【vue3+ts后台管理】登录页面完成

创建登录页面及其路由

创建 LoginView.vue,先随便写点什么

修改 index.ts 增加登录页的路由

const routes: Array<RouteRecordRaw> = [
  {...},
  {...},
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  }
]

然后在浏览器输入http://localhost:8080/login即可跳转登录页

登录页样式完成

修改 App.vue 完成基本样式

<template>
  <router-view/>
</template>

<style lang="scss">
*{
  padding: 0px;
  margin: 0px;
}

html,body,#app{
  width: 100%;
  height: 100%;
}
</style>

在Element plus 组件Form表单-自定义校验规则一节中,我们复制这里的代码,且进行修改即可。同时,把表单中需要的数据创建出来。其中关于表单验证可以参考:表单校验

LoginView.vue

<template>
  <div class="login-box">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
    >
      <h2>后台管理系统</h2>
      <el-form-item label="账号:" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" @click="submitForm(ruleFormRef)"
        >登录
        </el-button
        >
        <el-button class="login-btn" @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs} from "vue";

export default defineComponent({
  setup() {
    const data = reactive({
      ruleForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 3, max: 10, message: '账号的长度在3-10之间', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 10, message: '密码的长度在3-10之间', trigger: 'blur'},
        ],
      }
    })

    return {
      ...toRefs(data)
    }
  },
});
</script>

<style lang="scss" scoped>
.login-box {
  width: 100%;
  height: 100%;
  background: url("../assets/login-bg.jpeg");
  text-align: center;
  padding: 1px;
  .demo-ruleForm{
    width: 500px;
    margin: 200px auto;
    background: #ffffff;
    padding: 40px;
    border-radius: 5px;
  }
  .login-btn{
    width: 48%;
  }
  h2{
    margin-bottom: 20px;
  }
}
</style>

运行程序,页面如下:
【vue3+ts后台管理】登录页面完成_第1张图片

使用ts对数据类型进行规范

src 下新建 type 文件夹,其中新建 login.ts

export interface LoginForm {
    username: string
    password: string
}

export class LoginData {
    ruleForm: LoginForm = {
        username: "",
        password: ""
    }
}

修改 LoginView.vue

<script lang="ts">
import {defineComponent, reactive, toRefs} from "vue";
import {LoginData} from "@/type/login";

export default defineComponent({
  setup() {
    const data = reactive(new LoginData())

    const rules = {
      username: [
        {required: true, message: '请输入账号', trigger: 'blur'},
        {min: 3, max: 10, message: '账号的长度在3-10之间', trigger: 'blur'},
      ],
          password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 3, max: 10, message: '密码的长度在3-10之间', trigger: 'blur'},
      ],
    }

    return {
      ...toRefs(data),
      rules
    }
  },
});
</script>

重置

<el-button class="login-btn" @click="resetForm">重置</el-button>

<script lang="ts">
......

export default defineComponent({
  setup() {
  	......
    const resetForm = () => {
      data.ruleForm.username = "";
      data.ruleForm.password = "";
    }

    return {
      ...
      resetForm
    }
  },
});
</script>

封装axios

baseUrl:
https://www.fastmock.site/mock/bf1fcb3c2e2945669c2c8d0ecb8009b8/api

登录接口
地址:/login
方式: post
参数: username && password

商品列表接口
地址: /getGoodsList
方式: get

用户列表接口
地址: /getUserList
方式: get

角色列表接口
地址: /getRoleList
方式: get

权限列表接口
地址: /getAuthorityList
方式: get

首先我们需要安装 axios,执行npm install axios

在 src 下新建 request 文件夹,其中新建 index.ts

import axios from 'axios'

//创建axios实例
const service = axios.create({
    baseURL: 'https://www.fastmock.site/mock/bf1fcb3c2e2945669c2c8d0ecb8009b8/api',
    timeout: 5000,
    headers: {'Content-Type': 'application/json;charset=utf-8'}
});
//请求拦截
service.interceptors.request.use((config)=>{
    config.headers = config.headers || {}
    if(localStorage.getItem('token')){
        config.headers.token = localStorage.getItem('token') || ''
    }
    return config
})
//响应拦截
service.interceptors.response.use((res)=>{
    const code:number = res.data.code
    if(code != 200){
        return Promise.reject(res.data)
    }
    return res.data
},(error)=>{
    console.log(error)
})
export default service

登录逻辑的实现

request 下新建 api.ts

import service from "@/request/index";
interface loginData{
    username:string,
    password:string
}
export function login(data:loginData){
    return service({
        url:'/login',
        method:'post',
        data
    })
}

根据表单-自定义校验规则中的源码提交相关逻辑可以直接复制过来

LoginView完整代码如下:

<template>
  <div class="login-box">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
    >
      <h2>后台管理系统</h2>
      <el-form-item label="账号:" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-btn" @click="submitForm(ruleFormRef)"
        >登录
        </el-button
        >
        <el-button class="login-btn" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs,ref} from "vue";
import {LoginData} from "@/type/login";
import type { FormInstance, FormRules } from 'element-plus'
import {login} from "@/request/api";
import {useRouter} from "vue-router";

export default defineComponent({
  setup() {
    const data = reactive(new LoginData())
    const rules = {
      username: [
        {required: true, message: '请输入账号', trigger: 'blur'},
        {min: 3, max: 10, message: '账号的长度在3-10之间', trigger: 'blur'},
      ],
          password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 3, max: 10, message: '密码的长度在3-10之间', trigger: 'blur'},
      ],
    }
    const ruleFormRef = ref<FormInstance>()
    const router = useRouter()
    const submitForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          login(data.ruleForm).then((res)=>{
            //console.log(res)
            //保存token
            localStorage.setItem("token",res.data.token)
            //跳转
            router.push('/')
          })
        } else {
          console.log('error submit!')
          return false
        }
      })
    }
    //重置
    const resetForm = () => {
      data.ruleForm.username = "";
      data.ruleForm.password = "";
    }

    return {
      ...toRefs(data),
      rules,
      resetForm,
      ruleFormRef,
      submitForm
    }
  },
});
</script>

<style lang="scss" scoped>
.login-box {
  width: 100%;
  height: 100%;
  background: url("../assets/login-bg.jpeg");
  text-align: center;
  padding: 1px;
  .demo-ruleForm{
    width: 500px;
    margin: 200px auto;
    background: #ffffff;
    padding: 40px;
    border-radius: 5px;
  }
  .login-btn{
    width: 48%;
  }
  h2{
    margin-bottom: 20px;
  }
}
</style>

由于我们的接口是模拟登录,所以正确的账号密码分别是:
账号:admin
密码:123456

当我们点击登录时,可以输出 res 来看下返回结果:
【vue3+ts后台管理】登录页面完成_第2张图片
运行程序结果如下:
【vue3+ts后台管理】登录页面完成_第3张图片

你可能感兴趣的:(Vue学习笔记,vue.js,前端)