十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
今天就跟大家聊聊有關(guān)Vue的路由及路由鉤子函數(shù)的實現(xiàn),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

10余年建站經(jīng)驗, 做網(wǎng)站、成都網(wǎng)站建設(shè)客戶的見證與正確選擇。創(chuàng)新互聯(lián)公司提供完善的營銷型網(wǎng)頁建站明細(xì)報價表。后期開發(fā)更加便捷高效,我們致力于追求更美、更快、更規(guī)范。
什么是路由
什么是路由?網(wǎng)絡(luò)原理中,路由指的是根據(jù)上一接口的數(shù)據(jù)包中的IP地址,查詢路由表轉(zhuǎn)發(fā)到另一個接口,它決定的是一個端到端的網(wǎng)絡(luò)路徑。
web中,路由的概念也是類似,根據(jù)URL來將請求分配到指定的一個'端'。(即根據(jù)網(wǎng)址找到能處理這個URL的程序或模塊)
使用vue.js構(gòu)建項目,vue.js本身就可以通過組合組件來組成應(yīng)用程序;當(dāng)引入vue-router后,我們需要處理的是將組件(components)映射到路由(routes),然后在需要的地方進(jìn)行使用渲染。
其所包含的功能有:
嵌套的路由/視圖表
模塊化的、基于組件的路由配置
路由參數(shù)、查詢、通配符
基于 Vue.js 過渡系統(tǒng)的視圖過渡效果
細(xì)粒度的導(dǎo)航控制
帶有自動激活的 CSS class 的鏈接
HTML5 歷史模式或 hash 模式,在 IE9 中自動降級
自定義的滾動條行為
1、基礎(chǔ)路由
當(dāng)我們通過 vue create 創(chuàng)建項目的的時候,會選擇是否安裝vue-router,項目創(chuàng)建后,在主組件App.vue中的HTML部分:
Hello App!
Go to Foo Go to Bar
上述代碼中,
2、在router/index.js文件中
// 0. 如果使用模塊化機(jī)制編程,導(dǎo)入Vue和VueRouter,要調(diào)用 Vue.use(VueRouter)
// 1. 定義 (路由) 組件。 可以從其他文件 import 進(jìn)來
const Foo = { template: 'foo' }
// 2. 定義路由每個路由應(yīng)該映射一個組件。 其中"component" 可以是通過 Vue.extend() 創(chuàng)建的組件構(gòu)造器,或者,只是一個組件配置對象。
const routes = [
{ path: '/foo', component: Foo },
]
// 3. 創(chuàng)建 router 實例,然后傳 `routes` 配置
const router = new VueRouter({
routes
})
// 4. 創(chuàng)建和掛載根實例。通過 router 配置參數(shù)注入路由,從而讓整個應(yīng)用都有路由功能
const app = new Vue({
router
}).$mount('#app')3、動態(tài)路由
什么是動態(tài)路由?動態(tài)路由是指路由器能夠自動的建立自己的路由表,并且能夠根據(jù)實際情況的變化實時地進(jìn)行調(diào)整。
1、在vue項目中,使用vue-router如果進(jìn)行不傳遞參數(shù)的路由模式,則稱為靜態(tài)路由;如果能夠傳遞參數(shù),對應(yīng)的路由數(shù)量是不確定的,此時的路由稱為動態(tài)路由。動態(tài)路由,是以冒號為開頭的(:),例子如下:
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
}, {
path: '/RouterComponents/:id',
name: 'RouterComponents',
component: RouterComponents
}
]
})一個“路徑參數(shù)”使用冒號 : 標(biāo)記。當(dāng)匹配到一個路由時,參數(shù)值會被設(shè)置到 this.$route.params,可以在每個組件內(nèi)使用。
2、路由跳轉(zhuǎn),執(zhí)行方式有兩大類;
第一大類:router-link模式,直接把參數(shù)寫在to屬性里面:
跳轉(zhuǎn)
第二大類:$router.push()模式,代碼如下:
methods: {
changeFuc (val) {
this.$router.push({
name: 'RouterComponents',
params: {id: val}
})
}
}或者:
methods: {
changeFuc (val) {
this.$router.push({
path: `/RouterComponents/${val}`,
})
}
}4、路由嵌套
vue項目中,界面通常由多個嵌套的組件構(gòu)成;同理,URL中的動態(tài)路由也可以按照某種結(jié)構(gòu)對應(yīng)嵌套的各層組件:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 當(dāng) /user/:id/profile 匹配成功,
// UserProfile 會被渲染在 User 的 中
path: 'profile',
component: UserProfile
},
{
// 當(dāng) /user/:id/posts 匹配成功
// UserPosts 會被渲染在 User 的 中
path: 'posts',
component: UserPosts
}
]
}
]
}) 5、捕獲所有路由或404 NotFound路由
常規(guī)參數(shù)只會匹配被 / 分隔的 URL 片段中的字符。如果想匹配任意路徑,我們可以使用通配符 (*):
{
// 會匹配所有路徑
path: '*'
}
{
// 會匹配以 `/user-` 開頭的任意路徑
path: '/user-*'
}當(dāng)使用通配符路由時,請確保路由的順序是正確的,也就是說含有通配符的路由應(yīng)該放在最后。路由 { path: '*' } 通常用于客戶端 404 錯誤。如果你使用了History 模式,請確保正確配置你的服務(wù)器。
6、編程式導(dǎo)航
| 聲明式 | 編程式 |
|---|---|
| router.push(...) |
想要導(dǎo)航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當(dāng)用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。
當(dāng)你點擊
// 字符串
router.push('home')
// 對象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
// 帶查詢參數(shù),變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})如果提供了 path,params 會被忽略
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 這里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user7、命名路由
由于我們需要通過不同的路由跳轉(zhuǎn)到不同的頁面,這時給我們的路由都加一個名字操作起來會比較方便
const router = new VueRouter({
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
})User
8、命名視圖
有時候我們需要一個布局,這時候,我們就需要用到命名視圖。
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})9、嵌套命名視圖
{
path: '/settings',
// 你也可以在頂級路由就配置命名視圖
component: UserSettings,
children: [{
path: 'emails',
component: UserEmailsSubscriptions
}, {
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview
}
}]
}10、路由組件傳參
在組件中使用 $route 會使之與其對應(yīng)路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
使用 props 將組件和路由解耦:
取代與 $route 的耦合
const User = {
template: 'User {{ $route.params.id }}'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})通過 props 解耦
const User = {
props: ['id'],
template: 'User {{ id }}'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 對于包含命名視圖的路由,你必須分別為每個命名視圖添加 `props` 選項:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})路由鉤子
1、路由鉤子
在某些情況下,當(dāng)路由跳轉(zhuǎn)前或跳轉(zhuǎn)后、進(jìn)入、離開某一個路由前、后,需要做某些操作,就可以使用路由鉤子來監(jiān)聽路由的變化
全局路由鉤子:router.beforeEach 注冊一個全局前置守衛(wèi)
router.beforeEach((to, from, next) => {
//會在任意路由跳轉(zhuǎn)前執(zhí)行,next一定要記著執(zhí)行,不然路由不能跳轉(zhuǎn)了
console.log('beforeEach')
console.log(to,from)
//
next()
})
//
router.afterEach((to, from) => {
//會在任意路由跳轉(zhuǎn)后執(zhí)行
console.log('afterEach')
})單個路由鉤子:
只有beforeEnter,在進(jìn)入前執(zhí)行,to參數(shù)就是當(dāng)前路由
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]路由組件鉤子:
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用
// 不!能!獲取組件實例 `this`
// 因為當(dāng)守衛(wèi)執(zhí)行前,組件實例還沒被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
// 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候,
// 由于會渲染同樣的 Foo 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。
// 可以訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用
// 可以訪問組件實例 `this`
}附:完整的導(dǎo)航解析流程
導(dǎo)航被觸發(fā)。
在失活的組件里調(diào)用離開守衛(wèi)。
調(diào)用全局的 beforeEach 守衛(wèi)。
在重用的組件里調(diào)用 beforeRouteUpdate 守衛(wèi) (2.2+)。
在路由配置里調(diào)用 beforeEnter。
解析異步路由組件。
在被激活的組件里調(diào)用 beforeRouteEnter。
調(diào)用全局的 beforeResolve 守衛(wèi) (2.5+)。
導(dǎo)航被確認(rèn)。
調(diào)用全局的 afterEach 鉤子。
觸發(fā) DOM 更新。
用創(chuàng)建好的實例調(diào)用 beforeRouteEnter 守衛(wèi)中傳給 next 的回調(diào)函數(shù)。
2、路由元信息
定義路由的時候可以配置 meta 字段:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
// a meta field
meta: { requiresAuth: true }
}
]
}
]
})看完上述內(nèi)容,你們對Vue的路由及路由鉤子函數(shù)的實現(xiàn)有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。