什么是路由
什么是路由?網絡原理中,路由指的是根據上一接口的數據包中的IP地址,查詢路由表轉發到另一個接口,它決定的是一個端到端的網絡路徑。
web中,路由的概念也是類似,根據URL來將請求分配到指定的一個'端'。(即根據網址找到能處理這個URL的程序或模塊)
使用vue.js構建項目,vue.js本身就可以通過組合組件來組成應用程序;當引入vue-router后,我們需要處理的是將組件(components)映射到路由(routes),然后在需要的地方進行使用渲染。
其所包含的功能有:
1、基礎路由
當我們通過 vue create 創建項目的的時候,會選擇是否安裝vue-router,項目創建后,在主組件App.vue中的HTML部分:
<script src="https://unpkg.com/vue/dist/vue.js"></script><script src="https://unpkg.com/vue-router/dist/vue-router.js"></script><div id="app"> <h1>Hello App!</h1> <p> <!-- 使用 router-link 組件來導航. --> <!-- 通過傳入 `to` 屬性指定鏈接. --> <!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這里 --> <router-view></router-view></div>
上述代碼中,<router-view/>是路由出口,路由匹配到的組件將渲染在這里。
2、在router/index.js文件中
// 0. 如果使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter)// 1. 定義 (路由) 組件。 可以從其他文件 import 進來const Foo = { template: '<div>foo</div>' }// 2. 定義路由每個路由應該映射一個組件。 其中"component" 可以是通過 Vue.extend() 創建的組件構造器,或者,只是一個組件配置對象。const routes = [ { path: '/foo', component: Foo }, ]// 3. 創建 router 實例,然后傳 `routes` 配置const router = new VueRouter({ routes })// 4. 創建和掛載根實例。通過 router 配置參數注入路由,從而讓整個應用都有路由功能const app = new Vue({ router}).$mount('#app')3、動態路由
什么是動態路由?動態路由是指路由器能夠自動的建立自己的路由表,并且能夠根據實際情況的變化實時地進行調整。
1、在vue項目中,使用vue-router如果進行不傳遞參數的路由模式,則稱為靜態路由;如果能夠傳遞參數,對應的路由數量是不確定的,此時的路由稱為動態路由。動態路由,是以冒號為開頭的(:),例子如下:
export default new Router({ routes: [  {   path: '/',   name: 'HelloWorld',   component: HelloWorld  }, {   path: '/RouterComponents/:id',   name: 'RouterComponents',   component: RouterComponents  } ]})一個“路徑參數”使用冒號 : 標記。當匹配到一個路由時,參數值會被設置到 this.$route.params,可以在每個組件內使用。
2、路由跳轉,執行方式有兩大類;
第一大類:router-link模式,直接把參數寫在to屬性里面:
<router-link :to="{name:'RouterComponents',params:{id:110}}">跳轉</router-link>第二大類:$router.push()模式,代碼如下:
methods: {  changeFuc (val) {   this.$router.push({    name: 'RouterComponents',    params: {id: val}   })  }}或者:
methods: {  changeFuc (val) {   this.$router.push({    path: `/RouterComponents/${val}`,   })  }}4、路由嵌套
vue項目中,界面通常由多個嵌套的組件構成;同理,URL中的動態路由也可以按照某種結構對應嵌套的各層組件:
const router = new VueRouter({ routes: [  { path: '/user/:id', component: User,   children: [    {     // 當 /user/:id/profile 匹配成功,     // UserProfile 會被渲染在 User 的 <router-view> 中     path: 'profile',     component: UserProfile    },    {     // 當 /user/:id/posts 匹配成功     // UserPosts 會被渲染在 User 的 <router-view> 中     path: 'posts',     component: UserPosts    }   ]  } ]})5、捕獲所有路由或404 NotFound路由
常規參數只會匹配被 / 分隔的 URL 片段中的字符。如果想匹配任意路徑,我們可以使用通配符 (*):
{ // 會匹配所有路徑 path: '*'}{ // 會匹配以 `/user-` 開頭的任意路徑 path: '/user-*'}當使用通配符路由時,請確保路由的順序是正確的,也就是說含有通配符的路由應該放在最后。路由 { path: '*' } 通常用于客戶端 404 錯誤。如果你使用了History 模式,請確保正確配置你的服務器。
6、編程式導航
| 聲明式 | 編程式 | 
|---|---|
| <router-link :to="..."> | router.push(...) | 
想要導航到不同的 URL,則使用 router.push 方法。這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。
當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 <router-link :to="..."> 等同于調用 router.push(...)。
// 字符串router.push('home')// 對象router.push({ path: 'home' })// 命名的路由router.push({ name: 'user', params: { userId: '123' }})// 帶查詢參數,變成 /register?plan=privaterouter.push({ path: 'register', query: { plan: 'private' }})如果提供了 path,params 會被忽略
const userId = '123'router.push({ name: 'user', params: { userId }}) // -> /user/123router.push({ path: `/user/${userId}` }) // -> /user/123// 這里的 params 不生效router.push({ path: '/user', params: { userId }}) // -> /user7、命名路由
由于我們需要通過不同的路由跳轉到不同的頁面,這時給我們的路由都加一個名字操作起來會比較方便
const router = new VueRouter({ routes: [  {   path: '/user/:userId',   name: 'user',   component: User  } ]})<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>8、命名視圖
有時候我們需要一個布局,這時候,我們就需要用到命名視圖。
<router-view class="view one"></router-view><router-view class="view two" name="a"></router-view><router-view class="view three" name="b"></router-view>
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 會使之與其對應路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
使用 props 將組件和路由解耦:
取代與 $route 的耦合
const User = { template: '<div>User {{ $route.params.id }}</div>'}const router = new VueRouter({ routes: [  { path: '/user/:id', component: User } ]})通過 props 解耦
const User = { props: ['id'], template: '<div>User {{ id }}</div>'}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、路由鉤子
在某些情況下,當路由跳轉前或跳轉后、進入、離開某一個路由前、后,需要做某些操作,就可以使用路由鉤子來監聽路由的變化
全局路由鉤子:router.beforeEach 注冊一個全局前置守衛
router.beforeEach((to, from, next) => {  //會在任意路由跳轉前執行,next一定要記著執行,不然路由不能跳轉了 console.log('beforeEach') console.log(to,from) // next()})//router.afterEach((to, from) => {  //會在任意路由跳轉后執行 console.log('afterEach')})單個路由鉤子:
只有beforeEnter,在進入前執行,to參數就是當前路由
 routes: [  {   path: '/foo',   component: Foo,   beforeEnter: (to, from, next) => {    // ...   }  } ]路由組件鉤子:
 beforeRouteEnter (to, from, next) {  // 在渲染該組件的對應路由被 confirm 前調用  // 不!能!獲取組件實例 `this`  // 因為當守衛執行前,組件實例還沒被創建 }, beforeRouteUpdate (to, from, next) {  // 在當前路由改變,但是該組件被復用時調用  // 舉例來說,對于一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,  // 由于會渲染同樣的 Foo 組件,因此組件實例會被復用。而這個鉤子就會在這個情況下被調用。  // 可以訪問組件實例 `this` }, beforeRouteLeave (to, from, next) {  // 導航離開該組件的對應路由時調用  // 可以訪問組件實例 `this` }附:完整的導航解析流程
2、路由元信息
定義路由的時候可以配置 meta 字段:
const router = new VueRouter({ routes: [  {   path: '/foo',   component: Foo,   children: [    {     path: 'bar',     component: Bar,     // a meta field     meta: { requiresAuth: true }    }   ]  } ]})以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答