route的區(qū)別
理解:
router可以理解為一個(gè)容器管理了一組
route是進(jìn)行當(dāng)前ULR和組件的映射關(guān)系,它包含了很多的屬性和對象(比如history對象),任何頁面都可以調(diào)用他的push(),replace(),go()等方法
const router = new Router({
routes: [
{
path: '/',
name: 'home',
component: home,
},
{
path: '/login',
name: 'login',
component: login
},
{
path: '/about',
name: 'about',
component: about,
beforeEnter:(to,from,next)=>{
// console.log('路由獨(dú)享守衛(wèi)to',to);
// console.log('路由獨(dú)享守衛(wèi)from',from);
next()
}
}
]
})
$route是當(dāng)前激活的路由,包含了當(dāng)前激活的路由狀態(tài)信息,它包含了當(dāng)前URL解析得到的信息.
$router對象的屬性
- $router.app: 配置了
router的Vue根實(shí)例 - $router.mode: 路由使用的模式
- $router.currentRoute: 當(dāng)前路由對應(yīng)的路由信息對象
$router鉤子函數(shù)調(diào)用順序圖

$router對象方法
$router.beforeEach(to,from,next):是$router的鉤子函數(shù),全局前置守衛(wèi),異步解析執(zhí)行,通常做一些攔截比如:登錄攔截.$router.beforeResolve(to,from,next): 和$router.beforeEach(to,from,next)基本類似,區(qū)別是:$router.beforeResolve(to,from,next)的調(diào)用時(shí)機(jī)是在beforeEach和組件內(nèi)的beforeRouteEnter之后,afterEach之前調(diào)用.$router.afterEach(to, from): 全局后置鉤子他是在路由跳轉(zhuǎn)完成后觸發(fā),參數(shù)包括to,from沒有了next,他發(fā)生在beforeEach和beforeResolve之后,beforeRouteEnter之前.$router.push: 編程式導(dǎo)航,使用push方法,會(huì)導(dǎo)航到不同的URL,會(huì)想history添加新的記錄,$router.replace: 和push很像,區(qū)別是它不會(huì)向history添加記錄,會(huì)替換當(dāng)前的history.$router.go(n): 方法的參數(shù)是一個(gè)整數(shù), 會(huì)在history記錄中向前或者后退多少步,和window.history.go(n)類似$router.back(): 編程式導(dǎo)航,后退一步記錄,等同于$router.go(-1)。$history.forward(): 編程式導(dǎo)航,前進(jìn)一步記錄,等同于$router.go(1)。-
router.resolve: 解析目標(biāo)位置,格式和<router-link>的to prop相同,current是當(dāng)前默認(rèn)的路由.使用場景如下:使用
router.resolve自定義一個(gè)頁面跳轉(zhuǎn)的方法Vue.prototype.$linkTo = function ({ path, query, type }) { if (typeof (arguments[0]) != 'object') { // 跳轉(zhuǎn)路徑 path = arguments[0]; } // 請求參數(shù) query = query || {}; // 跳轉(zhuǎn)類型 type = type || '_self'; let routeData = router.resolve({ path: path, query: query || {} }) console.log('router.resolve()的返回值:', routeData) window.open(routeData.href, type); }調(diào)用
<button @click="$linkTo({ path: '/about'})">去about頁面</button> 點(diǎn)擊這么button后會(huì)跳轉(zhuǎn)到about頁面,resolve的作用就是解析參數(shù)成一個(gè)完整的url
$route對象屬性
-
$route.path: 返回字符串,對應(yīng)當(dāng)前路由的路徑 -
$route.parms: 一個(gè) key/value 對象,包含了 動(dòng)態(tài)片段 和 全匹配片段,如果沒有路由參數(shù),就是一個(gè)空對象。 -
$route.query: 一個(gè) key/value 對象,表示 URL 查詢參數(shù)。例如,對于路徑/foo?user=1,則有$route.query.user == 1,如果沒有查詢參數(shù),則是個(gè)空對象。 -
$route.fullPath: 完成解析后的 URL,包含查詢參數(shù)和 hash 的完整路徑。 -
$route.name: 當(dāng)前路由的名稱,如果有的話