【Vue】13 VueRouter Part3 路由守衛
阿新 • • 發佈:2020-07-26
單頁應用中,只存在一個HTML檔案,網頁的標籤,是通過title標籤顯示的,我們在單頁應用中如何修改?
JS操作:
window.document.title = "標籤名稱"
也許一兩個沒問題,但是我們的Vue元件越來越多,修改就難了
所以就需要路由守衛了
鉤子函式:
beforeEach
afterEach
這兩個函式用於路由改變的前後觸發執行
在我們的index.js中配置meta物件,這是網頁的元資訊標籤
import Vue from 'vue'; import VueRouter from "vue-router"; // 匯入路由外掛 import home from"../components/home"; import sample from "../components/sample"; import news from "../components/news"; import msg from "../components/msg"; Vue.use(VueRouter); //注入路由外掛 const routes = [ { path : '/home', component : home, meta : { title : "主頁" }, children : [ // 配置子路由 { path : 'news/:id', component : news, meta : { title : "新聞頁" }, }, { path :'msg', component : msg, meta : { title : "訊息頁" }, } ] }, { path : '/sample', component : sample, meta : { title : "樣本頁" }, }, ]; // 定義路由 const router = new VueRouter({ // 建立路由例項 routes, mode : 'history' }); export default router; // 匯出路由例項
然後編寫路由的鉤子方法:
// 建立路由例項,使用路由守衛 router.beforeEach((to,from,next) => {// to 目標路由物件,from 當前路由物件,next該方法執行後進入 window.document.title = to.meta.title; next(); });
效果:
或者設定統一的攔截處理