Vue Router路由守衛(wèi)超詳細介紹
全局前置&后置路由守衛(wèi)
router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import List from '@/pages/List'
Vue.use(VueRouter);
const router = new VueRouter({
routes: [{
path: '/list',
component: List,
meta: { // 路由元數據
title: '列表'
... // 可自定義配置參數
}
}]
});
// 前置:在路由切換之前調用
router.beforeEach((to, from, next) => {});
// 后置:在路由切換成功之后調用
router.afterEach((to, from) => {});
export default router;
說明
① router.beforeEach()是全局前置路由守衛(wèi)
② router.afterEach()是全局后置路由守衛(wèi)
③ to:目的地路由信息
④ from: 出發(fā)地路由信息
⑤ next:是個函數,只有調用next(),路由器才可繼續(xù)跳轉,不調用直接攔截
⑥ routes中的meta配置項,可配置一些自定義的參數
獨享路由守衛(wèi)
router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import List from '@/pages/List';
import Detail from '@/pages/Detail';
Vue.use(VueRouter);
export default new VueRouter({
routes: [{
path: '/list',
component: List,
children: [{
path: 'detail',
component: Detail,
// Detail組件獨享此路由守衛(wèi)
beforeEnter: (to, from, next) => {}
}]
}]
});
說明
① 組件內部的beforeEnter()是獨享前置路由守衛(wèi)
② 獨享路由守衛(wèi)只有前置沒有后置
③ 獨享路由守衛(wèi)與全局路由守衛(wèi)可一起搭配使用
組件內路由守衛(wèi)
Detail組件
<template>
<div></div>
</template>
<script>
export default {
name: 'Detail',
// 通過路由,進入組件之前調用
beforeRouteEnter(to, from, next) {},
// 通過路由,離開組件之前調用
beforeRouteLeave(to, from, next) {}
}
</script>
說明
① beforeRouteEnter(),通過路由,進入組件之前被調用
② beforeRouteLeave(),通過路由,離開組件之前被調用
③ 兩者都需要調用next()放行
到此這篇關于Vue Router路由守衛(wèi)超詳細介紹的文章就介紹到這了,更多相關Vue Router路由守衛(wèi)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決vue里a標簽值解析變量,跳轉頁面,前面加默認域名端口的問題
這篇文章主要介紹了解決vue里a標簽值解析變量,跳轉頁面,前面加默認域名端口的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
vue vantUI tab切換時 list組件不觸發(fā)load事件的問題及解決方法
這篇文章主要介紹了vue vantUI tab切換時 list組件不觸發(fā)load事件的解決辦法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02

