安裝路由
npm i vue-router -S
引入路由
import VueRouter form VueRouter
注入路由模塊
Vue.use(VueRouter)
定義路由匹配規則
let routes = [
{...},
{...}
]
上列匹配規則中 對象有如下屬性
path : 路由路徑
component : 所加載的組件
name : 別名
redirect : 重定向
children : 子級路由
創建路由實例
let router = new VueRouter({
routes : routes //routes屬性值應該為上述路由匹配規則數組
})
將路由實例注入到初始化代碼中
let app = new Vue({
data:...,
router : router
})
跳轉:
標簽跳轉
<router-link to="" ></router-link>
該標簽擁有屬性
to : 目標路徑 也可以是對象
tag: 指定該標簽解析成實際的標簽類型
activeClass: 指定選中時的class名
js跳轉(編程式導航)
在組件內:
this.$router.push()
this.$router.replace()
this.$router.go() 前進或者后退 正前負退
路由傳參
傳統search傳參(?號傳參)
傳送數據
標簽傳參
<router-link :to="{name:'...',query:data}"></router-link>
編程傳參
this.$router.push({
name : "...",
query : data
})
接收數據
this.$route.query
路徑傳參(動態路由)
路由配置:
{path:"/detail/:id",component:....}
傳送數據:
<router-link :to="{name:'...',params:data}">
編程傳參:
this.$router.push({name:'...',params:data})
接收參數
this.$route.params
路由守衛(導航守衛)
路由的鈎子函數
三大類
全局
決定跳轉前
router.beforeEach((to,from,next)=>{})
to代表目標路徑對象
from代表來源路徑對象
next() 是否繼續 參數有三種
true或者不傳 代表允許跳轉
false 代表中止跳轉
填入路徑 會重定向到指定路徑
決定跳轉后但還沒有跳轉時 此時無法阻止路由跳轉
router.afterEach((to,from)=>{})
路由獨享
{path:"....",beforeEnter((to,from,next)=>{})}
組件守衛
進入當前組件前
beforeRouteEnter((to,from,next)=>{})
離開當前組件前
beforeRouteLeave((to,from,next)=>{})
路徑沒有變化但是參數變化時(多用於監聽單純的參數變化)
beforeRouteUpdate((to,from,next)=>{})