一、路由的簡(jiǎn)介
1、實(shí)現(xiàn)生活中的路由
路由:路由其實(shí)就是一個(gè)key-value對(duì)應(yīng)關(guān)系
路由器:用于管理多個(gè)路由關(guān)系的設(shè)備被稱(chēng)為路由器
2、前端的路由
目前使用的前端項(xiàng)目都是單頁(yè)面的應(yīng)用(SPA),一個(gè)項(xiàng)目中只有一個(gè)html頁(yè)面,這種項(xiàng)目是由很多個(gè)組件組成,組件之間如果要跳轉(zhuǎn)要依靠路由來(lái)完成,路由是由key和value組成一個(gè)對(duì)應(yīng)關(guān)系,前端路由的key就是url地址,路由的value就是組件本身
key | value |
---|---|
http://localhost:8080/login | Login.vue |
http://localhost:8080/register | Register.vue |
總之:路由是實(shí)現(xiàn)多個(gè)組件之間進(jìn)行跳轉(zhuǎn)一種方式,使用路由將各組件之間聯(lián)系起來(lái)
由于vue是一個(gè)漸進(jìn)式的前端框架,vue的核心語(yǔ)法中不包括路由,路由以插件的形式存在,如果要去使用路由就要去將路由集成到vue項(xiàng)目中
二、路由的基本配置
1、路由的配置
由于路由不是vue的核心功能,大家如果要使用就需要去單獨(dú)集成它,在vue中使用路由最多一個(gè)路由產(chǎn)品vue-router
vue-router的官網(wǎng):Vue Router
注意:vue2的項(xiàng)目,匹配的路由版本是vue-router@3
配置的具體步驟如下
-
安裝vue-router的依賴包
npm install vue-router@3.5.1
-
在src目錄創(chuàng)建router的文件夾,在router文件夾下創(chuàng)建index.js文件,具體代碼如下
//導(dǎo)入Vue包
import Vue from 'vue'
//導(dǎo)入VueRouter包
import VueRouter from 'vue-router'
//將VueRouter作為插件設(shè)置到Vue中
Vue.use(VueRouter)
//創(chuàng)建路由器對(duì)象
const router=new VueRouter()
//將這個(gè)路由器對(duì)象導(dǎo)出
export default router
-
將路由掛載到vue實(shí)例上,在main.js文件中
import Vue from 'vue'
import App from './App.vue'
import router from '@/router'
Vue.config.productionTip = false
?
new Vue({
?render: h => h(App),
?router
}).$mount('#app')
?
2、一級(jí)路由的配置
路由是一個(gè)key-value的對(duì)應(yīng)關(guān)系
-
創(chuàng)建組件
在src/views目錄下分別創(chuàng)建Login.vue、Register.vue、Home.vue
-
路由配置
在src/router/index.js進(jìn)行如下配置
//導(dǎo)入Vue包
import Vue from 'vue'
//導(dǎo)入VueRouter包
import VueRouter from 'vue-router'
//導(dǎo)入組件
import Login from '@/views/Login'
import Register from '@/views/Register'
import Home from '@/views/Home'
//將VueRouter作為插件設(shè)置到Vue中
Vue.use(VueRouter)
//創(chuàng)建routes數(shù)組
const routes=[
? {
? ? ? ?path:'/login',
? ? ? ?component:Login
? },
? {
? ? ? ?path:'/register',
? ? ? ?component:Register
? },
? {
? ? ? ?path:'/home',
? ? ? ?component:Home
? }
]
/*
創(chuàng)建路由器對(duì)象
const router=new VueRouter(config)
config:路由的配置對(duì)象
routes:路由配置的數(shù)組
*/
const router=new VueRouter({
? ?routes
})
//將這個(gè)路由器對(duì)象導(dǎo)出
export default router
3、路由的出口設(shè)置
如上已經(jīng)將路由的規(guī)則配置成功了,如果要顯示在頁(yè)面上,就需要配置路由出口
在App.vue根組件中配置路由出口
<template>
? ?<router-view></router-view>
</template>
4、路由的跳轉(zhuǎn)
使用vue-router進(jìn)行路由跳轉(zhuǎn)有兩種方式
-
標(biāo)簽式跳轉(zhuǎn)方式:使用
<router-link>
這個(gè)標(biāo)簽進(jìn)行跳轉(zhuǎn),一般使用在<template></template>
模板之中,最終會(huì)編譯成<a>
標(biāo)簽 -
編程式跳轉(zhuǎn)方式:使用
this.$router
對(duì)象的push
或者replace
方法進(jìn)行跳轉(zhuǎn)的,這種跳轉(zhuǎn)方式一般使用在組件的js代碼部分
4.1、標(biāo)簽式路由跳轉(zhuǎn)的案例
已有賬號(hào)?<router-link to="/login">前往登錄</router-link>
4.2、編程式路由跳轉(zhuǎn)
-
下載axios
npm i axios
-
配置package.json
"scripts": {
? ?"serve": "vue-cli-service serve",
? ?"serve:production": "set NODE_ENV=production&vue-cli-service serve",
? ?"build": "vue-cli-service build"
}
-
封裝auth.js方法,完成token獲取和設(shè)置的封裝
位置:src/utils/auth.js
const tokenkey="admin-token"
// 保存token到localStorage中的方法
export const setToken=tokenval=>localStorage.setItem(tokenkey,tokenval)
// 從localStorage中獲取token
export const getToken=()=>localStorage.getToken(tokenkey)
-
封裝axios
位置:src/api/request.js
import axios from 'axios'
import {getToken} from '@/utils/auth'
/*
基礎(chǔ)路由的配置
*/
switch(process.env.NODE_ENV){
case 'production':
axios.defaults.baseURL="http://47.98.128.191:3000/"
break;
default:
axios.defaults.baseURL="http://www.zhaijizhe.cn:3005"
break
}
/*
設(shè)置請(qǐng)求攔截器
*/
axios.interceptors.request.use(config=>{
//獲取token的信息,然后將token信息攜帶到請(qǐng)求頭信息中
if(getToken){
config.headers.Authorization=getToken()
}
return config
})
/*
設(shè)置響應(yīng)攔截器
*/
axios.interceptors.response.use(response=>{
return response.data
},err=>{
if(err.response){
switch(err.response.status){
case 401:
break
case 404:
break
case 500:
break
}
}
})
export default axios
-
編寫(xiě)登錄api方法
位置:src/api/modules/users.js
import request from '@/api/request'
export default{
login:(data)=>request.post('/users/login',data)
}
-
匯總模塊
位置:src/api/api.js
import users from "./modules/users";
export default{
users
}
-
掛載api到Vue原型上
位置:src/main.js
import api from '@/api/api'
Vue.prototype.$api=api
-
組件中完成登錄
位置:src/views/Login.vue
<template>
<div>
<h1>登錄</h1>
<div>
沒(méi)有賬號(hào)?<router-link to="/register">前往注冊(cè)</router-link>
</div>
<div>
<div>
<label for="username">姓名:</label>
<input id="username" type="text" placeholder="請(qǐng)輸入登錄賬戶" v-model="user.username">
</div>
<div>
<label for="password">密碼:</label>
<input id="password" type="text" placeholder="請(qǐng)輸入登錄賬戶" v-model="user.password">
</div>
<div>
<button @click="login">登錄</button>
</div>
</div>
</div>
</template>
<script>
import {setToken} from '@/utils/auth'
export default {
data(){
return{
user:{
username:'admin',
password:'123'
}
}
},
methods:{
async login(){
let {code,message,token}=await this.$api.users.login(this.user)
/*
登錄成功后,要完成的事項(xiàng)有兩個(gè)
1、保存token到localStorage中
2、使用路由進(jìn)行跳轉(zhuǎn)
*/
setToken(token)
if(code){
alert(message)
//跳轉(zhuǎn)到后臺(tái),使用編程式路由跳轉(zhuǎn)
this.$router.replace('/home')
}
}
}
}
</script>
<style>
</style>
5、路由的嵌套
-
如果要配置二級(jí)路由,需要在相應(yīng)的一級(jí)路由對(duì)象上添加children屬性,然后進(jìn)行配置
位置:src/router/index.js
{
path:'/home',
component:Home,
children:[
{
path:'workplace',//二級(jí)路由的path的前不要帶/
component:workplace
},
{
path:'analysis',
component:analysis
},
{
path:'studentList',
component:studentList
}
]
}
-
靜態(tài)菜單
位置:src/views/Home.vue
<template>
<div class="container">
<div class="header">
<div class="logo">學(xué)苑BOSS系統(tǒng)</div>
</div>
<div class="main">
<div class="silder">
<ul>
<li>
<span>控制面板</span>
<ul class="sul">
<li>
<router-link to="/home/workplace">工作臺(tái)</router-link>
</li>
<li>
<router-link to="/home/analysis">統(tǒng)計(jì)報(bào)表</router-link>
</li>
</ul>
</li>
<li>
<span>學(xué)員管理</span>
<ul class="sul">
<li>
<router-link to="/home/studentList">學(xué)生列表</router-link>
</li>
</ul>
</li>
<li>
<span>系統(tǒng)管理</span>
<ul class="sul">
<li>班主任管理</li>
<li>教師管理</li>
<li>專(zhuān)業(yè)管理</li>
<li>班級(jí)管理</li>
</ul>
</li>
</ul>
</div>
<div class="content">
<!-- 設(shè)置二級(jí)路由的出口 -->
<router-view></router-view>
</div>
</div>
</div>
</template>
<script>
export default {
}
</script>
三、路由的其他配置
1、路由的重定向
所謂的路由重定向就是指當(dāng)你輸入一個(gè)路由的路徑時(shí)候,它會(huì)自動(dòng)重新跳轉(zhuǎn)到另外一個(gè)路由上這種行為稱(chēng)為路由重定向
{
path:'/',
redirect:'/home'
},
2、路由懶加載
為了提高首屏加載速度,可以采用路由懶加載的方式,提升加載性能,避免白屏現(xiàn)象出現(xiàn)
//導(dǎo)入Vue包
import Vue from 'vue'
//導(dǎo)入VueRouter包
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//創(chuàng)建routes數(shù)組
const routes=[
{
path:'/login',
component:()=>import('@/views/Login')
},
{
path:'/register',
component:()=>import('@/views/Register')
},
{
path:'/',
redirect:'/home'
},
{
path:'/home',
component:()=>import('@/views/Home'),
children:[
{
path:'workplace',//二級(jí)路由的path的前不要帶/
component:()=>import('@/views/dashboard/workplace.vue')
},
{
path:'analysis',
component:()=>import('@/views/dashboard/analysis.vue')
},
{
path:'studentList',
component:()=>import('@/views/students/studentList.vue')
}
]
}
]
const router=new VueRouter({
routes
})
//將這個(gè)路由器對(duì)象導(dǎo)出
export default router
3、緩存路由
-
為需要設(shè)計(jì)緩存組件取一個(gè)名稱(chēng)
export default {
name:'analysis'
}
-
在路由的出口的地方設(shè)置keep-alive
<keep-alive exclude="analysis">
<router-view></router-view>
</keep-alive>
-
exclude
:該組件不被緩存 -
include
:該組件會(huì)被緩存
4、路由的元信息
路由對(duì)象有很多屬性,核心有兩個(gè),一個(gè)就是path,表示的路由的路徑,component表示的是路由的對(duì)應(yīng)的組件,除此之外還有其他的屬性,比如meta屬性,可以設(shè)置路由的額外信息,這里以兩個(gè)例子給大家講解
4.1、面包屑的功能
-
需要在路由定義的時(shí)候在相應(yīng)的路由配置對(duì)象中添加meta屬性,配置面包屑的具體配置
{
path:'workplace',//二級(jí)路由的path的前不要帶/
component:()=>import('@/views/dashboard/workplace.vue'),
meta:{
firstTitle:'控制面板',
secondTitle:'工作臺(tái)'
}
},
-
自定義面包屑組件
在src/components目錄下創(chuàng)建BreadCrumb組件
<template>
<div>
<span>{{$route.meta.firstTitle}}</span>><span>{{$route.meta.secondTitle}}</span>
</div>
</template>
-
在需要的組件中引入面包屑組件
<template>
<div>
<bread-crumb></bread-crumb>
<h1>學(xué)生列表</h1>
</div>
</template>
4.2、路由緩存狀態(tài)設(shè)置
-
在路由配置中為meta屬性設(shè)置isKeepAlive屬性
{
path:'workplace',//二級(jí)路由的path的前不要帶/
component:()=>import('@/views/dashboard/workplace.vue'),
meta:{
firstTitle:'控制面板',
secondTitle:'工作臺(tái)',
iskeepAlive:true
}
},
-
在路由出口的地方通過(guò)v-if指令來(lái)完成設(shè)置
<keep-alive>
<router-view v-if="$route.meta.iskeepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.iskeepAlive"></router-view>
說(shuō)明:這種設(shè)置方式較之前使用include或者exclude方式的更加合理。
四、路由傳參
1、學(xué)生列表
-
編寫(xiě)獲取學(xué)生的api方法
import request from '@/api/request'
export default{
getStudents:params=>request.get('/students/getStudents',{params})
}
-
匯總api
import users from "./modules/users";
import students from "./modules/students";
export default{
users,students
}
2、query傳參
vue-router這個(gè)路由操作中,要進(jìn)行傳參有多種方式,比較常用的方式有兩種
-
query傳參方式
-
params傳參方式
query傳參的步驟
第1步:創(chuàng)建頁(yè)面組件,配置路由
{
path:'studentDetail',
component:()=>import('@/views/students/studentDetail.vue'),
meta:{
firstTitle:'學(xué)生管理',
secondTitle:'學(xué)生詳情'
}
}
第2步:進(jìn)行傳參
-
標(biāo)簽跳轉(zhuǎn)的方式
<router-link :to="`/home/studentDetail?_id=${item._id}`"><button class="btn detal">查看</button></router-link>
<router-link :to="'/home/studentDetail?_id='+item._id"><button class="btn detal">查看</button></router-link>
<router-link :to="{path:'/home/studentDetail',query:{_id:item._id}}"><button class="btn detal">查看</button></router-link>
//命名路由
<router-link :to="{name:'xsxq',query:{_id:item._id}}"><button class="btn detal">查看</button></router-link>
最后一種寫(xiě)法是使用了命名路由的寫(xiě)法,命名路由的好處就是使用name來(lái)指定要跳轉(zhuǎn)位置
-
編程方式進(jìn)行跳轉(zhuǎn)
goStudentDetail(_id){
this.$router.push(`/home/studentDetail?_id=${_id}`)
}
goStudentDetail(_id){
this.$router.push('/home/studentDetail?_id='+_id)
}
goStudentDetail(_id){
this.$router.push({
path:'/home/studentDetail',
query:{
_id
}
})
}
goStudentDetail(_id){
this.$router.push({
name:'xsxq',
query:{
_id
}
})
}
第3步:接收路由參數(shù)
使用this.$route.query方式獲取參數(shù)
export default {
components:{BreadCrumb},
created(){
console.log(this.$route.query._id);
}
}
$router和$route
面試題(簡(jiǎn)單的面試題)
-
router:它是一個(gè)VueRouter類(lèi)型的一個(gè)對(duì)象,通過(guò)new VueRouter構(gòu)造函數(shù)方式將其創(chuàng)建出來(lái),它是一個(gè)全局對(duì)象
-
設(shè)置路由模式
-
實(shí)現(xiàn)路由跳轉(zhuǎn):通過(guò)該對(duì)象中push或者replace方法來(lái)實(shí)現(xiàn)跳轉(zhuǎn)的
-
-
route:路由信息對(duì)象,它屬于一個(gè)局部對(duì)象,該對(duì)象主要用來(lái)描述路由信息的
-
獲取該路由path路徑
-
獲取該路由的傳遞的參數(shù)(query參數(shù),params參數(shù))
-
獲取該路由的meta信息(用戶自定義的信息)
-
4、params傳參
動(dòng)態(tài)路由概念:所謂的動(dòng)態(tài)路由是指路由地址的一部分是變化的,像這種我們將其稱(chēng)為動(dòng)態(tài)路由
http://localhost:8080/#/home/studentUpadate/10001
http://localhost:8080/#/home/studentUpadate/10002
http://localhost:8080/#/home/studentUpadate/10003
如上操作,如果有多條信息,就需要在router/index.js中配置多個(gè)路由信息對(duì)象,這種做法不可取,原因有兩個(gè)
-
配置信息量特別大
-
這種配置不靈活
為了解決這個(gè)問(wèn)題,我們可以動(dòng)態(tài)路由的方式進(jìn)行配置,具體配置步驟如下
第1步:在路由配置文件中配置如下
{
path:'studentUpdate/:id',
component:()=>import('@/views/students/studentUpdate.vue'),
meta:{
firstTitle:'學(xué)生管理',
secondTitle:'修改學(xué)生'
}
}
第2步:路由跳轉(zhuǎn)傳參
根據(jù)跳轉(zhuǎn)方式的不同
-
標(biāo)簽方式跳轉(zhuǎn)
<router-link :to="`/home/studentUpdate/${item._id}`"><button class="btn detal">修改</button></router-link>
<router-link :to="'/home/studentUpdate/'+item._id"><button class="btn detal">修改</button></router-link>
-
編程方式跳轉(zhuǎn)
this.$router.push('/home/studentUpdate/'+_id)
this.$router.push(`/home/studentUpdate/${_id}`)
goStudentUpdate(_id){
this.$router.push({
name:'xsxg',
params:{
id:_id
}
})
}
注意:如果要使用push方法的參數(shù)是配置對(duì)象形式參數(shù),這種params只能和命名路由結(jié)合使用,不能和path一起使用
第3步:接收params參數(shù)
接收params參數(shù)有兩個(gè)方法
-
使用this.$route.params.參數(shù)名
console.log(this.$route.params.id);
-
使用props方式傳參
配置步驟
首先:在路由對(duì)象設(shè)置可以使用props方式接收
{
name:'xsxg',
path:'studentUpdate/:id',
component:()=>import('@/views/students/studentUpdate.vue'),
meta:{
firstTitle:'學(xué)生管理',
secondTitle:'修改學(xué)生'
},
props:true
}
其次:在接收參數(shù)的組件中設(shè)置props選項(xiàng)
export default {
props:['id'],
}
最后,在組件中使用
export default {
props:['id'],
components:{
BreadCrumb
},
created(){
// console.log(this.$route.params.id);
console.log('id:',this.id);
}
}
5、修改學(xué)生
-
頁(yè)面返回和頁(yè)面刷新
<button @click="$router.go(-1)">返回</button>
<button @click="$router.go(0)" >刷新</button>
五、路由模式【面試題】
由于Vue項(xiàng)目為單頁(yè)面應(yīng)用,所以整個(gè)項(xiàng)目在開(kāi)發(fā)和構(gòu)建過(guò)程中,僅存在一個(gè)HTML物理文件,通過(guò)路由系統(tǒng)可以實(shí)現(xiàn)將項(xiàng)目的組件與可訪問(wèn)的URL路徑進(jìn)行綁定。由于Vue項(xiàng)目只有一個(gè)HTML物理文件,切換頁(yè)面時(shí)既需要讓訪問(wèn)的URL路徑發(fā)生變化,又不能觸發(fā)HTML物理文件的重新加載,這就使得VueRouter的跳轉(zhuǎn)模式不能使用普通的超鏈接方式。
VueRouter為了支持單頁(yè)面應(yīng)用的頁(yè)面管理和頁(yè)面跳轉(zhuǎn),提供了兩種頁(yè)面跳轉(zhuǎn)和加載模式:
-
hash:在瀏覽器 URL 路徑中會(huì)有一個(gè)'#'
-
history:在瀏覽器 URL 路徑中沒(méi)有'#'
1、hash模式
hash模式使用了錨點(diǎn)技術(shù)重寫(xiě)URL訪問(wèn)路徑,會(huì)在原有的URL路徑后拼接/#/xx,這種方式可以在不重新加載原有HTML文件的基礎(chǔ)上,實(shí)現(xiàn)切換URL路徑的目的,hash模式的原理案例,代碼如下
<a href="#/index">首頁(yè)</a>
<a href="#/about">關(guān)于我們</a>
<div class="page index">
我是首頁(yè)
</div>
<div class="page about">
我是關(guān)于頁(yè)面
</div>
<script>
window.onhashchange=function(event){
var newURL=event.newURL.split("#/")[1]
var oldURL=event.oldURL.split("#/")[1]
var newPage=document.querySelector('.'+newURL)
var oldPage=document.querySelector('.'+oldURL)
newPage.style.display="block"
oldPage.style.display="none"
}
</script>
hash模式利用了純靜態(tài)技術(shù),解決了單頁(yè)面應(yīng)用的頁(yè)面劃分,它可以在不觸發(fā)網(wǎng)頁(yè)重新加載的情況下切換URL路徑,配合onhashchange可以實(shí)現(xiàn),一旦URL中的hash部分發(fā)生變化,就觸發(fā)函數(shù)通知,通過(guò)javascript編程便可以很快速的實(shí)現(xiàn)DOM對(duì)象的切換顯示。
hash模式同時(shí)也存在著不足之處,如在分布式微前端項(xiàng)目中,嵌套的子應(yīng)用和主應(yīng)用都使用hash模式時(shí),由于hash模式的URL路徑只能存在一個(gè)#,會(huì)導(dǎo)致子應(yīng)用和主應(yīng)用在定義URL路徑上存在著困難,hash模式的URL路徑中包含#,也會(huì)在視覺(jué)上導(dǎo)致URL路徑不美觀
2、history模式
histroy模式是VueRouter中常用的一種路由模式,它與hash模式不同,不需要借助錨點(diǎn)技術(shù)重寫(xiě)URL路徑,所以history模式使用的URL路徑中不存在#,在視覺(jué)上更加美觀,histroy模式采用histroy對(duì)象中的pushState()函數(shù)重寫(xiě)函數(shù)URL路徑,可在觸發(fā)重新加載的情況下變更URL路徑,history的原理,代碼如下
<a href="javascript:jump('/index')">跳轉(zhuǎn)到首頁(yè)</a>
<a href="javascript:jump('/about')">跳轉(zhuǎn)到about頁(yè)</a>
<div class="page index">
我是首頁(yè)
</div>
<div class="page about">
我是關(guān)于頁(yè)面
</div>
<script>
function jump(path){
history.pushState(null,'page',path)
var pages=document.querySelectorAll('.page')
var newPage=document.querySelector(path.replace("/","."))
pages.forEach(item=>item.style.display='none')
newPage.style.display='block'
}
</script>
history模式重寫(xiě)URL路徑的解決方案與hash模式現(xiàn)象類(lèi)似,但本質(zhì)不同,雖然histroy模式可以重寫(xiě)URL路徑,但是重寫(xiě)后的新路徑中并不包含原有HTML物理文件的訪問(wèn)路徑,所以history模式在重寫(xiě)URL路徑后,一旦刷新網(wǎng)頁(yè)會(huì)造成404無(wú)法訪問(wèn)的效果,VueCli在開(kāi)發(fā)環(huán)境中解決了history模式的刷新問(wèn)題,不過(guò)項(xiàng)目發(fā)布到生產(chǎn)環(huán)境時(shí),由于histroy模式的URL路徑問(wèn)題,還需要配合生產(chǎn)服務(wù)器的轉(zhuǎn)發(fā)規(guī)則重寫(xiě),用以支持history模式的路由加載。
可以在路由的配置文件中更改路由模式:
const router = new VueRouter({
routes: routes,
mode: 'history'
})
不設(shè)置 mode 屬性,則默認(rèn)為 hash 模式。
六、路由守衛(wèi)
1、什么是路由守衛(wèi)
當(dāng)路由發(fā)生變化的時(shí)候,會(huì)觸發(fā)的一些函數(shù),我們這些函數(shù)中編寫(xiě)一定業(yè)務(wù)邏輯,這種函數(shù)稱(chēng)為路由守衛(wèi)函數(shù),也有人稱(chēng)為導(dǎo)航守衛(wèi)
按照類(lèi)型將導(dǎo)航守衛(wèi)分為三大類(lèi)
-
全局前置守衛(wèi):當(dāng)所有路由被觸發(fā)的時(shí)候,在進(jìn)入指定組件之前所觸發(fā)的守衛(wèi)函數(shù)
-
路由獨(dú)享守衛(wèi):觸發(fā)指定路由的路由的時(shí)候觸發(fā)
-
組件內(nèi)守衛(wèi):當(dāng)離開(kāi)組件的時(shí)候,或者進(jìn)入組件的時(shí)候觸發(fā)的守衛(wèi)函數(shù)
2、全局前置守衛(wèi)
2.1、語(yǔ)法
router.beforeEach((to,from,next)=>{
})
參數(shù)說(shuō)明:
-
to:即將要進(jìn)入目標(biāo)路由對(duì)象
-
from:當(dāng)前導(dǎo)航正要離開(kāi)的路由
-
next:是一個(gè)函數(shù),該函數(shù)的作用是進(jìn)入到目標(biāo)路由所指定的組件,或者按照要求進(jìn)入到指定的組件
案例:防止沒(méi)有token直接進(jìn)入后臺(tái)
第1步:在router/index.js中編寫(xiě)路由全局前置守衛(wèi)函數(shù),完成token驗(yàn)證
router.beforeEach(async(to,from,next)=>{
console.log('********進(jìn)入路由全局前置守衛(wèi)************');
if(to.path=="/login"||to.path=="/register"){
console.log('即將要進(jìn)入的是登錄或者注冊(cè)組件');
//放行進(jìn)入
next()
}else{
//獲取token
let token=getToken()
if(token){
let result=await api.users.getUserInfo()
if(result.code){
next()//放行進(jìn)入
}
}else{
alert('您還沒(méi)有登錄,請(qǐng)先登錄')
next('/login')
}
}
})
第2步:在二次封裝axios的文件中request.js中補(bǔ)全401狀態(tài)時(shí)的執(zhí)行業(yè)務(wù)邏輯
axios.interceptors.response.use(response=>{
return response.data
},err=>{
if(err.response){
switch(err.response.status){
case 401:
console.log('進(jìn)入到攔截器的401處理中');
//彈框提示
alert('您的token已失效,請(qǐng)重新登錄')
//進(jìn)行路由跳轉(zhuǎn)
router.push('/login')
break
case 404:
break
case 500:
break
}
}
})
3、路由獨(dú)享守衛(wèi)
這種守衛(wèi)函數(shù),只針對(duì)于進(jìn)入該路由所觸發(fā)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-678599.html
{
path:'/home',
component:()=>import('@/views/Home'),
children:[
],
//如果進(jìn)入該路由或者該路由下的子路由都會(huì)進(jìn)入到這個(gè)守衛(wèi)函數(shù)
beforeEnter:async function(to,from,next){
let token=getToken()
if(token){
let {code}=await Vue.prototype.$api.users.getUserInfo()
if(code){
next()
}
}else{
alert('您還沒(méi)有登錄,請(qǐng)登錄')
next('/login')
}
}
}
4、組件內(nèi)守衛(wèi)
寫(xiě)在組件中文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-678599.html
beforeRouteEnter:async function(to,from,next){
console.log('------進(jìn)入該組件---------');
let result=await Vue.prototype.$api.users.getUserInfo()
if(result.data.auth==1){
console.log('------我是超級(jí)管理員-----------');
next()
}else if(result.data.auth==2){
console.log('-------我是普通管理員----------------------');
alert('您沒(méi)有權(quán)限進(jìn)入,請(qǐng)聯(lián)系系統(tǒng)管理,為您開(kāi)設(shè)權(quán)限')
}
// let result=await this.$api.users.getUserInfo()
// console.log('result',result);
},
beforeRouteLeave(to,from,next){
console.log('------離開(kāi)該組件----------');
if(this.name==''||this.fcz==''||this.startTime==''){
if(window.confirm('您還沒(méi)有輸入完所有的信息,您確認(rèn)你要離開(kāi)嗎?')){
next()
}
}
}
到了這里,關(guān)于VUE筆記(六)vue路由的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!