Simulation scenario:
When the user logs in, the background will return a token to the front-end. After the front-end enters the home page next time, it will first determine whether the token has expired. If it expires, it will automatically enter the login page.
Configure routing:
1. Installation
npm install vue-router@4
2. After installationsrc
Created in the directoryrouter folder
and createThe code is as follows:
// vue-router provides 3 routing modesimport { createWebHistory, createRouter } from 'vue-router' import { checktoken } from '../request/api'; const routes = [ { path: '/', name: "home", component: () => import('../components/Pages/'), }, { path: '/login', name: 'login', component: () => import('../components/Pages/'), } ] const router = createRouter({ //Routing mode history: createWebHistory(), // Routing rules routes }) //Navigation Guard Do some operations before navigation(async (to, from, next) => { // Write a function to check whether the token is valid if ( == 'home' && await checkTokenValidity()) { // If you enter the home page and are not authenticated, redirect to the login page next({ name: 'login' }); } else { // Other circumstances are allowed to pass next(); } }); async function checkTokenValidity() { // Get token const token = ('token'); if (token) { // Use ' ' to split the string const arr = (' '); let tokenstr = arr[1]; return await checktoken({ token: tokenstr }) } return true } export default router
Configure axios:
1. Installation
npm install axios
2. Insrc
Created inRequest folder
,andCreate and
3.
For packagingaxios
The example code is as follows:
// Introduce axios inimport axios from 'axios'; // Introduce axiosimport { ElMessage } from 'element-plus' const config={ // `url` is the server URL used for request url: '/api', // `baseURL` will be automatically added before `url` unless `url` is an absolute URL. // It can facilitate the passing of relative URLs to the axios instance method by setting a `baseURL` baseURL: 'http://localhost:56030/api', // `timeout` specifies the number of milliseconds for the request timeout (0 means no timeout) // If the request charge exceeds the timeout, the request will be interrupted timeout: 10000, } const requests = (config); //Request interceptor (you can do something before the request is sent)((config) => { return config; }); //Response interceptor (After the data is returned, do something) ( (res) => { return ; }, (err) => { (err); () } ) export default requests;
4.The code used for unified management of interfaces is as follows:
import requests from "./http"; //Introduce secondary encapsulation axiosexport const login = (params)=>requests({url:'/Account/login ',method:'post',data:params}); export const checktoken = (params)=>requests({url:'/Account/checktoken ',method:'post',data:params});
Use of routing and encapsulation interfaces
1. Log inComponents, just look at the usage here. The code is as follows:
<template> <el-card class="box-card"> <el-text class="title" type="warning" size="large">MetadataTechnology House</el-text> <div style="margin: 40px;"></div> <el-form label-position="top" label-width="100px" :model="formLabelAlign" style="max-width: 460px"> <el-form-item label="account"> <el-input v-model="" /> </el-form-item> <el-form-item label="password"> <el-input v-model="" type="password" /> </el-form-item> <el-button class="loginbut" type="primary" @click="onSubmit">Log in</el-button> </el-form> </el-card> </template> <script setup> import { reactive } from 'vue' import { login } from '../../request/api'; import { ElMessage } from 'element-plus' import { useRouter } from 'vue-router'; const router = useRouter(); const formLabelAlign = reactive({ accountNumber: 'admin', password: '123456' }) const onSubmit = async () => { var token = await login(formLabelAlign) if (token) { //Storage token [Authorize(AuthenticationSchemes = "Bearer")] ('token',"Bearer "+token); ElMessage({ message: 'Login successfully', type: 'success', }) // String path ('/'); } } </script> <style scoped> .el-card { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .box-card { width: 480px; height: 320px; } .title { position: absolute; left: 50%; transform: translate(-50%, -50%); } .loginbut { float: right; } </style>
This code is required to reference the route jump after login:
import { useRouter } from 'vue-router'; const router = useRouter(); // String path('/');
The code is as follows:
import { createApp } from 'vue' //Icons and components need to be introduced separatelyimport ElementPlus from 'element-plus'; // Introduce the ElementPlus componentimport 'element-plus/dist/' // Element Plus import 'element-plus/theme-chalk/' // Introduce ElementPlus component styleimport 'element-plus/theme-chalk/dark/' import { Edit } from '@element-plus/icons-vue' // Introduce Icons on demandimport router from './router/index' import App from './' const app = createApp(App) (router) ('Edit', Edit) (ElementPlus) // Global mount ElementPlus('#app')
Code:
<script> export default { }; </script> <template> <router-view></router-view> </template> <style scoped> .common-layout { height: 100vh; } .el-container { height: 100vh; } </style>
Give itCode and
Code can more conveniently see how routes are used.
This is the end of this article about the packaging usage tutorial for Vue router and axios in Vue. For more information about packaging usage of Vue router and axios, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!