Vue聲明式導(dǎo)航與編程式導(dǎo)航及導(dǎo)航守衛(wèi)和axios攔截器全面詳細講解
一、聲明式導(dǎo)航&編程式導(dǎo)航
1. 聲明式導(dǎo)航:以超鏈接方式實現(xiàn)的頁面跳轉(zhuǎn),就是聲明式導(dǎo)航
< a href=‘url’> 鏈接文本或圖像 < /a >
< router-link to=‘url’ > 鏈接文本或圖像 < /router-link >
2. 編程式導(dǎo)航:通過javascript提供的api方法實現(xiàn)頁面的跳轉(zhuǎn),就是編程式導(dǎo)航
location.href = ‘url’
location.go(number)
location.replace(‘url’)
3. vue-router中提供的編程式導(dǎo)航的API
? (1)this.$router.push(‘url’):將‘url’添加到路由表中,增加了一條路由記錄
<template>
<div>
<h3>Home 組件</h3>
<button @click="gotoMovie">跳轉(zhuǎn)到 Movie 頁面</button>
</div>
</template>
<script>
export default {
name: "",
methods:{
gotoMovie(){
this.$router.push('/movie/1')
}
}
}
</script>? (2)this.$router.replace(‘url’):跳轉(zhuǎn)到url中,并替換掉當前的歷史記錄
? push 和 replace 的區(qū)別:
? ? 1)push 會增加一條歷史記錄
? ? 2)replace 不會增加歷史記錄,而是替換掉當前的歷史記錄
? (3)this.$router.go(number):參數(shù)是一個數(shù)值,頁面跳轉(zhuǎn)到指定的位置,可以在瀏覽歷史中前進和后退。
? ? (4)this.$router.go()的簡化寫法
? ? ? 1)this.$router.back():在歷史記錄中,后退到上一個頁面
? ? ? 2)this.$router.forword():在歷史記錄中,前進到下一個頁面
<template>
<div>
<h3>Home 組件</h3>
<button @click="goBack">退回上一頁</button>
</div>
</template>
<script>
export default {
props:['id'],
methods:{
goBack(){
this.$router.go(-1)
}
}
}
</script>二、導(dǎo)航守衛(wèi)
1. 用途:在頁面導(dǎo)航過程中實現(xiàn)重定向、取消路由、權(quán)限驗證等業(yè)務(wù)。
? 導(dǎo)航守衛(wèi)分為三類:全局守衛(wèi)、路由獨享的守衛(wèi)、組件內(nèi)守衛(wèi),可以用于路由導(dǎo)航過程中的不同階段。
? 每一個導(dǎo)航守衛(wèi)都有三個參數(shù):to、from 和 next (router、afterEach 除外)

? 2. 分類:全局守衛(wèi)、組件內(nèi)部守衛(wèi)、路由獨享的守衛(wèi)
? 3. 全局守衛(wèi)
? ? (1)全局前置守衛(wèi):每次發(fā)生路由的導(dǎo)航跳轉(zhuǎn)時,都會觸發(fā)全局前置守衛(wèi)。因此,在全局前置守衛(wèi)中,程序員可以對每個路由進行訪問權(quán)限的控制。使用的router.beforeEach(to,from,next){ }來注冊。當一個導(dǎo)航觸發(fā)時,全局前置守衛(wèi)按照路由創(chuàng)建的順序調(diào)用。
- to:將要訪問的路由的信息對象
- from:將要離開的路由的信息對象
- ?next:是一個函數(shù),調(diào)用next()表示當前路由已經(jīng)放行
? ? (2)next調(diào)用的情況
? ? 1)用戶擁有了權(quán)限,直接放行:next()
? ? 2)用戶沒有權(quán)限,強制跳轉(zhuǎn)到指定的頁面:next(‘/login’)
? ? 3)用戶沒有權(quán)限,不允許訪問:next(false)

? ? 4. 全局前置守衛(wèi)的使用
? ? ? (1)創(chuàng)建Login.vue組件
? ? ? (2)在路由文件router / index.js中注冊全局的前置守衛(wèi)
//App.vue
<template>
<div>
<h2>{{ info }}</h2>
<div>
<label>
賬號:<input type="text" v-model.trim="userName" />
</label>
<br /><br />
<label>
密碼:<input type="password" v-model.trim="passWord" />
</label>
<br /><br />
<button type="button" @click="login">登錄</button>
</div>
</div>
</template>
<script type="text/javascript">
import $http from '../axios/index'
export default {
name: "Login",
data() {
return {
info: '',
userName: '',
passWord: '',
}
},
methods: {
login() {
// //對登陸信息進行驗證(實際中在此處進行ajax的請求)
// if('lisi' === this.userName && '1234' === this.passWord){
// sessionStorage.setItem('isAuth',true) //在頁面緩存中保存isAuth,isAuth=true表示用戶已登錄
// this.info = ''
// //判斷當前路由對象中參數(shù)是否有參數(shù)
// if(this.$route.query.redirect){
// let redirect =this.$route.query.redirect
// this.$router.replace(redirect)//跳轉(zhuǎn)到指定頁面
// }
// else{
// this.$router.replace('/')//若路由對象中沒有redirect,則直接跳轉(zhuǎn)到默認的首頁
// }
// }else{//非法用戶
// sessionStorage.setItem('isAuth',false)
// this.userName = ''
// this.passWord = ''
// this.info = '用戶名或密碼錯誤'
// }
$http.post('/test/login', {
userName: this.userName,
passWord: this.passWord
}).then(res => {
if (res.data.code == 200) {
sessionStorage.setItem('auth', res.data.tokenInfo)
this.info = ''
//判斷當前路由對象中參數(shù)是否有參數(shù)
if (this.$route.query.redirect) {
let redirect = this.$route.query.redirect
this.$router.replace(redirect)//跳轉(zhuǎn)到指定頁面
}
else {
this.$router.replace('/')//若路由對象中沒有redirect,則直接跳轉(zhuǎn)到默認的首頁
}
} else {
sessionStorage.setItem('auth', '')
this.userName = ''
this.passWord = ''
this.info = '用戶名或密碼錯誤'
}
})
}
}
}
</script>
<style scoped>
</style>//router/insex.js
//注冊全局前置導(dǎo)航守衛(wèi)
router.beforeEach((to, from, next) => {
//判斷目標路由是否是/login,如果是,則直接調(diào)用next()方法
if (to.path == '/login') {
next()
} else {//否則判斷用戶是否已經(jīng)登錄,注意這里是字符串判斷
if (sessionStorage.getItem('auth')!='' && sessionStorage.getItem('auth'!=null)) {
next()
} else {//如果用戶訪問的是受保護的資源,且沒有登錄,則跳轉(zhuǎn)到登錄頁面
//并將當前路由的完整路徑作為查詢參數(shù)傳遞給Login組件,以便登錄成功后返回先前的頁面
next({//強制跳轉(zhuǎn)到登錄頁面
path: '/login',
query:{ redirect:to.fullPath}
}
)
}
}
})三、axios攔截器
1. axios模塊的作用:是對基于http請求的封裝。在瀏覽器對異步請求對象XMLHttpRequest進行封裝
2. 攔截器
? (1)請求攔截器:對客戶端發(fā)起的請求進行統(tǒng)一的前期處理(token、時間戳、cookie等)
? (2)響應(yīng)攔截器:對服務(wù)器端響應(yīng)給客戶端的數(shù)據(jù)統(tǒng)一進行處理之后再發(fā)給客戶端

3. 使用方法
//前端/App.vue
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<br/> <br/>
<button @click="login">登錄</button>
<button @click="test">測試攔截器</button>
</div>
</template>
<script>
import $http from './axios/index'
export default {
name: 'App',
methods:{
login(){
$http.post('/users/login',{
userName:'lisi',
userPwd:'12345'
}).then(res=>{
if(res.data.code == 200){
sessionStorage.setItem('Auth',res.data.mytoken)
}
}).catch(err=>{
console.log(err);
})
},
test(){
$http.post('/users/test').then(res=>{
console.log(res.data);
}).catch(err=>{
console.log(err);
})
}
}
}
</script>//前端/index.js
import axios from "axios";
//1. 創(chuàng)建axios的實例,配置基礎(chǔ)路徑
const axiosInstance = axios.create({
baseURL: 'http://localhost:8089',
timeout: 5000
})
//2. 定義請求攔截器:給所有請求都帶上token
axiosInstance.interceptors.request.use((req) => {
let token = sessionStorage.getItem('Auth') //獲取頁面存儲中的token信息
if (token) { //若token存在
req.headers['Auth'] = token
}
return req;
}, (err) => {
return Promise.reject(err)
})
// 3.響應(yīng)攔截器:對服務(wù)器響應(yīng)給客戶端的數(shù)據(jù)進行統(tǒng)一的處理
axiosInstance.interceptors.response.use((res) => {
//1.對響應(yīng)數(shù)據(jù)進行處理
let result = res.data
let code = result.code
if (code == 200) {
return result
} else {
return Promise.reject(result)
}
}, (err) => {
return Promise.reject(err)
})
export default axiosInstance//后臺/usrs.js
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken')
/* http://localhost:8089/users/login */
router.post('/login', (req, res)=>{
//1.接收客戶的請求數(shù)據(jù)
let user = {
name:req.body.userName,
pwd:req.body.userPwd
}
//2.定義密鑰
let temp = 'baihualin'
//3.生成token
let token = jwt.sign(user,temp)
res.json({
code:200,
mytoken:token
})
} );
/* http://localhost:8089/users/login */
router.post('/test',(req,res)=>{
//輸出請求頭信息
console.log(req,headers)
let arr = [
{
bookId:1001,
bookName:'Vue2從入門到精通',
publish:'清華大學出版社'
},
{
bookId:1002,
bookName:'Html從入門到放棄',
publish:'清華大學出版社'
},
{
bookId:1003,
bookName:'Css都是浮云',
publish:'清華大學出版社'
},
]
res.json(arr)
})
module.exports = router;到此這篇關(guān)于Vue聲明式導(dǎo)航與編程式導(dǎo)航及導(dǎo)航守衛(wèi)和axios攔截器全面詳細講解的文章就介紹到這了,更多相關(guān)Vue聲明式導(dǎo)航內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue導(dǎo)出el-table表格為Excel文件的兩種方式
在開發(fā)過程中,我們經(jīng)常需要將表格數(shù)據(jù)導(dǎo)出為 Excel 文件,大多數(shù)情況下,由后端處理即可,但是當數(shù)據(jù)量不大、需要快速響應(yīng)用戶操作、或者數(shù)據(jù)已經(jīng)在前端進行處理和展示時,前端該如何實現(xiàn)呢,本文將介紹兩種方法,需要的朋友可以參考下2024-09-09
vue-cli或vue項目利用HBuilder打包成移動端app操作
這篇文章主要介紹了vue-cli或vue項目利用HBuilder打包成移動端app操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
使用Vue?Query實現(xiàn)高級數(shù)據(jù)獲取的示例詳解
構(gòu)建現(xiàn)代大規(guī)模應(yīng)用程序最具挑戰(zhàn)性的方面之一是數(shù)據(jù)獲取,這也是?Vue?Query?庫的用途所在,下面就跟隨小編一起學習一下如何利用Vue?Query實現(xiàn)高級數(shù)據(jù)獲取吧2023-08-08
使用vue實現(xiàn)點擊按鈕滑出面板的實現(xiàn)代碼
這篇文章主要介紹了使用vue實現(xiàn)點擊按鈕滑出面板的實現(xiàn)代碼,非常不錯,具有參考借鑒價值,需要的朋友參考下2017-01-01

