Vue中Vue router和axios的封裝使用教程
模擬場景:
當(dāng)用戶登錄后,后臺(tái)會(huì)返回一個(gè)token給前端,前端下次進(jìn)入首頁后,會(huì)先判斷token是否過期,如果過期自動(dòng)進(jìn)入登錄頁面。
配置路由:
1.安裝
npm install vue-router@4
2.安裝后在src
目錄下創(chuàng)建router文件夾
,并創(chuàng)建index.js
代碼如下:
// vue-router中提供3種的路由模式 import { createWebHistory, createRouter } from 'vue-router' import { checktoken } from '../request/api'; const routes = [ { path: '/', name: "home", component: () => import('../components/Pages/Home.vue'), }, { path: '/login', name: 'login', component: () => import('../components/Pages/Login.vue'), } ] const router = createRouter({ // 路由的模式 history: createWebHistory(), // 路由規(guī)則 routes }) //導(dǎo)航守衛(wèi) 導(dǎo)航前做點(diǎn)操作 router.beforeEach(async (to, from, next) => { // 編寫一個(gè)函數(shù)來檢查 token 是否有效 if (to.name == 'home' && await checkTokenValidity()) { // 如果進(jìn)入首頁且未認(rèn)證,則重定向到登錄頁 next({ name: 'login' }); } else { // 其他情況允許通過 next(); } }); async function checkTokenValidity() { // 獲取 token const token = localStorage.getItem('token'); if (token) { // 使用 ' ' 分割字符串 const arr = token.split(' '); let tokenstr = arr[1]; return await checktoken({ token: tokenstr }) } return true } export default router
配置axios:
1.安裝
npm install axios
2.在src
中創(chuàng)建request文件夾
,并創(chuàng)建http.js和api.js
3.http.js
用于封裝axios
實(shí)例 代碼如下:
// 在http.js中引入axios import axios from 'axios'; // 引入axios import { ElMessage } from 'element-plus' const config={ // `url` 是用于請求的服務(wù)器 URL url: '/api', // `baseURL` 將自動(dòng)加在 `url` 前面,除非 `url` 是一個(gè)絕對 URL。 // 它可以通過設(shè)置一個(gè) `baseURL` 便于為 axios 實(shí)例的方法傳遞相對 URL baseURL: 'http://localhost:56030/api', // `timeout` 指定請求超時(shí)的毫秒數(shù)(0 表示無超時(shí)時(shí)間) // 如果請求話費(fèi)了超過 `timeout` 的時(shí)間,請求將被中斷 timeout: 10000, } const requests = axios.create(config); //請求攔截器(可以在請求發(fā)出去之前,做一些事情) requests.interceptors.request.use((config) => { return config; }); //響應(yīng)攔截器(在數(shù)據(jù)返回之后,做一些事情) requests.interceptors.response.use( (res) => { return res.data; }, (err) => { console.log(err); ElMessage.error(err.response.data) } ) export default requests;
4.api.js
用于對接口的統(tǒng)一管理 代碼如下:
import requests from "./http"; //引入二次封裝的axios export const login = (params)=>requests({url:'/Account/login ',method:'post',data:params}); export const checktoken = (params)=>requests({url:'/Account/checktoken ',method:'post',data:params});
對路由和封裝接口的使用
1.登錄login.vue
組件,這里只看用法即可。 代碼如下:
<template> <el-card class="box-card"> <el-text class="title" type="warning" size="large">Metadata科技屋</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="賬號"> <el-input v-model="formLabelAlign.accountNumber" /> </el-form-item> <el-form-item label="密碼"> <el-input v-model="formLabelAlign.password" type="password" /> </el-form-item> <el-button class="loginbut" type="primary" @click="onSubmit">登錄</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) { // 存儲(chǔ) token [Authorize(AuthenticationSchemes = "Bearer")] localStorage.setItem('token',"Bearer "+token); ElMessage({ message: '登錄成功', type: 'success', }) // 字符串路徑 router.push('/'); } } </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>
登錄成功后的路由跳轉(zhuǎn)需要引用這句代碼:
import { useRouter } from 'vue-router'; const router = useRouter(); // 字符串路徑 router.push('/');
main.js代碼如下:
import { createApp } from 'vue' // 圖標(biāo)和組件需要分開引入 import ElementPlus from 'element-plus'; // 引入 ElementPlus 組件 import 'element-plus/dist/index.css' // Element Plus import 'element-plus/theme-chalk/index.css' // 引入 ElementPlus 組件樣式 import 'element-plus/theme-chalk/dark/css-vars.css' import { Edit } from '@element-plus/icons-vue' // 按需引入 Icon 圖標(biāo) import router from './router/index' import App from './App.vue' const app = createApp(App) app.use(router) app.component('Edit', Edit) app.use(ElementPlus) // 全局掛載 ElementPlus app.mount('#app')
app.vue
代碼:
<script> export default { }; </script> <template> <router-view></router-view> </template> <style scoped> .common-layout { height: 100vh; } .el-container { height: 100vh; } </style>
給出main.js代碼和app.vue
代碼,可以更方便的看出路由的使用方式。
到此這篇關(guān)于Vue中Vue router和axios的封裝使用教程的文章就介紹到這了,更多相關(guān)Vue router和axios的封裝使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Element中的Cascader(級聯(lián)列表)動(dòng)態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法
這篇文章主要介紹了Element中的Cascader(級聯(lián)列表)動(dòng)態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03詳解為element-ui的Select和Cascader添加彈層底部操作按鈕
這篇文章主要介紹了詳解為element-ui的Select和Cascader添加彈層底部操作按鈕,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02vue-router路由參數(shù)刷新消失的問題解決方法
本篇文章主要介紹了vue-router路由參數(shù)刷新消失的問題解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Vue3.0 響應(yīng)式系統(tǒng)源碼逐行分析講解
這篇文章主要介紹了Vue3.0 響應(yīng)式系統(tǒng)源碼逐行分析講解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10vue.js內(nèi)部自定義指令與全局自定義指令的實(shí)現(xiàn)詳解(利用directive)
這篇文章主要給大家介紹了關(guān)于vue.js內(nèi)部自定義指令與全局自定義指令的實(shí)現(xiàn)方法,vue.js中實(shí)現(xiàn)自定義指令的主要是利用directive,directive這個(gè)單詞是我們寫自定義指令的關(guān)鍵字,需要的朋友們下面跟著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-07-07