從零開始學VUE之VueRouter(導航守衛)
阿新 • • 發佈:2021-06-28
導航守衛
需要先定義路由,然後通過路由物件呼叫
import Vue from 'vue' // 匯入路由 import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' // import home from '../components/Home' // import about from '../components/About' // import user from '../components/User' const home = () => import('../components/Home') consthomeNews = () => import('../components/HomeNews') const homeMessage = () => import('../components/HomeMessage') const about = () => import('../components/About') const user = () => import('../components/User') const profile = () => import('../components/Profile') // Vue載入 Vue.use(Router) // 傳入路由對映配置 匯出路由例項const router = new Router({ // 設定模式為 history mode: 'history', linkActiveClass: 'active', linkExactActiveClass: 'noactive', routes: [// 傳遞引數的佔位符 { // 在預設的情況下 重定向到主頁 path: '', redirect: "/home" }, { path: '/user/:userId', name: 'user', meta:{ title: '使用者' }, component: user }, { path:'/home', name: 'home', meta:{ title: '首頁' }, component: home, // 巢狀路由 children: [ { path: 'news', meta:{ title: '首頁|新聞' }, component: homeNews }, { path: 'message', meta:{ title: '首頁|訊息' }, component: homeMessage }, { path: '', redirect: 'news' } ] }, { path: '/about', name: 'about', meta:{ title: '關於' }, component: about }, { // 傳遞引數 path:'/profile', meta:{ title: '檔案' }, component:profile } ] }) // 前置守衛函式 router.beforeEach((to, from, next) => { // 路由導航守衛 // 在路由跳轉呼叫之前 // from 從哪裡 to 到哪裡 // document.title = to.matched[0].meta.title; document.title = to.meta.title; // 呼叫next放行路由 next(); }) // 後置鉤子函式 router.afterEach((to,from) => { }) export default router
作者:彼岸舞
時間:2021\06\28
內容關於:VUE
本文屬於作者原創,未經允許,禁止轉發