Vue聲明式導航與編程式導航及導航守衛(wèi)和axios攔截器全面詳細講解
一、聲明式導航&編程式導航
1. 聲明式導航:以超鏈接方式實現(xiàn)的頁面跳轉(zhuǎn),就是聲明式導航
< a href=‘url’> 鏈接文本或圖像 < /a >
< router-link to=‘url’ > 鏈接文本或圖像 < /router-link >
2. 編程式導航:通過javascript提供的api方法實現(xiàn)頁面的跳轉(zhuǎn),就是編程式導航
location.href = ‘url’
location.go(number)
location.replace(‘url’)
3. vue-router中提供的編程式導航的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>
二、導航守衛(wèi)
1. 用途:在頁面導航過程中實現(xiàn)重定向、取消路由、權限驗證等業(yè)務。
? 導航守衛(wèi)分為三類:全局守衛(wèi)、路由獨享的守衛(wèi)、組件內(nèi)守衛(wèi),可以用于路由導航過程中的不同階段。
? 每一個導航守衛(wèi)都有三個參數(shù):to、from 和 next (router、afterEach 除外)
? 2. 分類:全局守衛(wèi)、組件內(nèi)部守衛(wèi)、路由獨享的守衛(wèi)
? 3. 全局守衛(wèi)
? ? (1)全局前置守衛(wèi):每次發(fā)生路由的導航跳轉(zhuǎn)時,都會觸發(fā)全局前置守衛(wèi)。因此,在全局前置守衛(wèi)中,程序員可以對每個路由進行訪問權限的控制。使用的router.beforeEach(to,from,next){ }來注冊。當一個導航觸發(fā)時,全局前置守衛(wèi)按照路由創(chuàng)建的順序調(diào)用。
- to:將要訪問的路由的信息對象
- from:將要離開的路由的信息對象
- ?next:是一個函數(shù),調(diào)用next()表示當前路由已經(jīng)放行
? ? (2)next調(diào)用的情況
? ? 1)用戶擁有了權限,直接放行:next()
? ? 2)用戶沒有權限,強制跳轉(zhuǎn)到指定的頁面:next(‘/login’)
? ? 3)用戶沒有權限,不允許訪問: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 //注冊全局前置導航守衛(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)響應攔截器:對服務器端響應給客戶端的數(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的實例,配置基礎路徑 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.響應攔截器:對服務器響應給客戶端的數(shù)據(jù)進行統(tǒng)一的處理 axiosInstance.interceptors.response.use((res) => { //1.對響應數(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;
到此這篇關于Vue聲明式導航與編程式導航及導航守衛(wèi)和axios攔截器全面詳細講解的文章就介紹到這了,更多相關Vue聲明式導航內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue2.0實現(xiàn)點擊其他區(qū)域關閉自定義div功能
這篇文章主要介紹了vue2.0實現(xiàn)點擊其他區(qū)域關閉自定義div功能實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06