Vue + element UI realizes complete login and exit functions

Time:2022-5-10

Then the last article began to record. The last problem of the last article has been solved, and I forgot: the cause. Modification completed. So far, the login and logout function has been realized. Here is my code:

Login.vue

<template>
  <div class="login_container">
    <div class="login_box">
      <!-- Head -- >
      <div class="avatar_box">
        <img>
      </div>
      <!-- Login form area -- >
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">
        <!-- User name -- >
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
        </el-form-item>
        <!-- Password -- >
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="iconfont icon-3702mima" type="password"></el-input>
        </el-form-item>
        <!-- Button area -- >
        <el-form-item class="btns">
          < El button type = "primary" @ Click = "login" > login < / El button >
          < El button type = "info" @ Click = "resetloginform" > Reset < / El button >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      //This is the data binding object of the login form
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      //This is the object of the form rule
      loginFormRules: {
        //Verify whether the user name is legal
        username: [
          {
            required: true,
            Message: 'please enter login name',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            Message: 'the length is between 3 and 10 characters',
            trigger: 'blur'
          }
        ],
        //Verify whether the password is legal
        password: [
          {
            required: true,
            Message: 'please enter the password',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            Message: 'the length is between 6 and 15 characters',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    //Click the reset button
    resetLoginForm () {
      // console.log(this)
      //Resetfields method reset in element UI
      this.$refs.loginFormRef.resetFields()
    },
    login () {
      //Form pre validation
      this.$refs.loginFormRef.validate(async valid => {
        If (! Valid) return // if the form fails the verification, it will be returned directly
        //{data: res}: Rename data to res
        const { data: res } = await this.$http.post('login', this.loginForm)
        console.log(res.meta)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$ message. Success ('login succeeded ')
        // 1. Save the token after successful login to the sessionstorage of the client
        //1.1 interfaces other than login in the project can only be accessed after login
        //1.2 the token should only take effect during the opening of the current website, so save the token to sessionstorage
        //Sessionstorage is a session saving mechanism, while localstorage is a persistent storage mechanism
        console.log(res)
        window.sessionStorage.setItem('token', res.data.token)
        // 2. Jump to the background home page through programmed navigation, and the routing address is / home
        this.$router.push('/home')
        //Git push - U origin login pushes the local branch to the code cloud
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
}

.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  //Div centered
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}

.btns {
  display: flex;
  justify-content: flex-end;
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './plugins/element.js'
import './assets/global.css'
import './assets/fonts/iconfont.css'
import axios from 'axios'
//Configure the root path of the request
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
//Mount Axios on the Vue prototype object, and Vue components can access Axios through this
Vue.prototype.$http = axios

Vue.config.productionTip = false

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

Home.vue

<template>
  <div>
    < El button type = "info" @ Click = "logout" > Exit < / El button >
  </div>
</template>

<script>
export default {
  methods: {
    logout () {
      window.sessionStorage.clear()
      this.$router.push('/login')
    }
  }
}
</script>

<style lang="less" scoped>

</style>

index.js

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

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  }, {
    path: '/',
    redirect: '/login'
  }, {
    path: '/home',
    component: Home
  }
]

const router = new VueRouter({
  routes
})

//Mount route navigation guard
router.beforeEach((to, from, next) => {
  //To the path to be accessed
  //From stands for which path to jump from
  //Next is a function that indicates release
  //Next() release next ('/ Login') forced jump
  if (to.path === '/login') return next()
  //Get token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})
export default router

Finally, put the renderings~
Vue + element UI realizes complete login and exit functions
Vue + element UI realizes complete login and exit functions
OK, next, continue to improve the function of the home page and record later