路由別名
在main.js中的路由中添加name來創建別名
const routes = [ {path:'/footer',name:footerLink,component:Footer} ]
在組件中的路由中通過對象屬性來實現路由
<router-link :to="{name:homeLink}">Mirror微申</router-link>
跳轉
1.跳轉到上一次瀏覽的頁面
this.$router.go(-1)
2.跳轉到指定路由
this.$router.replace(‘/footer’) // 還可以通過別名跳轉 this.$router.replace({name:’footerLink’})
也可以通過push進行
this.$router.push(‘/footer’) this.$router.push({name:’footerLink’})
設置默認路由
const routes = [ {path:'/',redirect:'/home'}, {path:'/home',name:homeLink,component:Home}, ]
或者在路由中添加
const routes = [ {path:'*',redirect:'/'}, ]
這樣寫有兩個好處,一個是設置了默認訪問路由,還有一個就是當用戶在地址欄輸入錯誤的時候跳轉到首頁
二級路由
剝離路由,單獨寫在一個文件中
1.將路由提取到一個文件中,我把它放在了main.js 同目錄到
./assets/js/routes.js
import Home from '../../components/home/Home'; import Footer from "../../components/footer/Footer"; export const routes = [ { path: '/', name: 'homeLink', component: Home }, { path: '/footer', name: 'footerLink', component: Footer }, { path: '*', redirect: '/' }, ]
說明,使用 export 將數組暴露出去,import引入組件
2.在main.js 中引入路由文件
import { routes } from './assets/js/routes.js'
路由守衛
1.全局守衛
// 全局守衛
router.beforeEach((to,from,next)=>{
if(to.path == '/login' || to.path == '/register'){ next(); }else{ alert("你還沒有登錄,請先登陸"); next('/login'); } })
參數說明:
to:去那
from:到哪里
next:跳轉到哪里,回調函數
2.后置鈎子
在路由之后出發,其實和全局守衛差不多
router.afterEach((to,from) => { alert("后置鈎子"); })
3.獨享守衛
就是在路由中添加 beforeEnter ,訪問其他鏈接的時候,不會提示,只有在訪問特定路由的時候才會觸發
{ path: '/blogging', name: 'bloggingLink', component: Blogging ,beforeEnter: (to, from, next) => { if(to.path == '/login' || to.path == '/register'){ next(); }else{ alert("你還沒有登錄,請先登陸"); next('/login'); } }},
4.組件內守衛
就是在組件內進行守衛,不能和路由守衛同用
export default { data(){ return { name:'Victor' } }, // 組件進入 beforeRouteEnter (to, from, next) { next(vm => { alert('Hello ' + this.name) }) }, // 組件離開 beforeRouteLeave (to, from, next) { if(confirm('確認離開嗎?') == true) { next(); }else{ next(false); } } }
說明:在 beforeRouteEnter 中如果想訪問data,需要在回調中訪問