Vue中Vue router和axios的封裝使用教程
模擬場景:
當用戶登錄后,后臺會返回一個token給前端,前端下次進入首頁后,會先判斷token是否過期,如果過期自動進入登錄頁面。
配置路由:
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
})
//導航守衛(wèi) 導航前做點操作
router.beforeEach(async (to, from, next) => {
// 編寫一個函數(shù)來檢查 token 是否有效
if (to.name == 'home' && await checkTokenValidity()) {
// 如果進入首頁且未認證,則重定向到登錄頁
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實例 代碼如下:
// 在http.js中引入axios
import axios from 'axios'; // 引入axios
import { ElMessage } from 'element-plus'
const config={
// `url` 是用于請求的服務器 URL
url: '/api',
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
// 它可以通過設置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URL
baseURL: 'http://localhost:56030/api',
// `timeout` 指定請求超時的毫秒數(shù)(0 表示無超時時間)
// 如果請求話費了超過 `timeout` 的時間,請求將被中斷
timeout: 10000,
}
const requests = axios.create(config);
//請求攔截器(可以在請求發(fā)出去之前,做一些事情)
requests.interceptors.request.use((config) => {
return config;
});
//響應攔截器(在數(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) {
// 存儲 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'
// 圖標和組件需要分開引入
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 圖標
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)列表)動態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法
這篇文章主要介紹了Element中的Cascader(級聯(lián)列表)動態(tài)加載省\市\(zhòng)區(qū)數(shù)據(jù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
詳解為element-ui的Select和Cascader添加彈層底部操作按鈕
這篇文章主要介紹了詳解為element-ui的Select和Cascader添加彈層底部操作按鈕,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
vue-router路由參數(shù)刷新消失的問題解決方法
本篇文章主要介紹了vue-router路由參數(shù)刷新消失的問題解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
vue.js內(nèi)部自定義指令與全局自定義指令的實現(xiàn)詳解(利用directive)
這篇文章主要給大家介紹了關(guān)于vue.js內(nèi)部自定義指令與全局自定義指令的實現(xiàn)方法,vue.js中實現(xiàn)自定義指令的主要是利用directive,directive這個單詞是我們寫自定義指令的關(guān)鍵字,需要的朋友們下面跟著小編來一起學習學習吧。2017-07-07

