1. 程式人生 > 實用技巧 >Vue Router(1)

Vue Router(1)

寫在前面

在上篇部落格 前端路由 中是根據原生的 Web API 手動構建的前端路由器。在 Vue 框架中,Vue 官方有提供對應的路由管理器,就是 Vue Router。無論是哪種前端路由管理工具,實現思路基本是一致的。因此在學習 Vue Router 的使用方法時,應從 路由表、路由連結、路由內容等 進行記憶。

1. 是什麼

Vue Router 是 vue.js 官方的路由管理器。

2. 基本用法

2.1 安裝 vue-router 到專案中

安裝:
yarn add vue-router
引入:

import VueRouter from 'vue-router'

Vue.use(VueRouter)

2.2 定義路由表

const routes = [
  {path: '/a', component: A},
  {path: '/b', component: B}
]

2.3 建立 VueRouter 例項

const router = new VueRouter({
  routes,
  mode: 'history' //路由模式選擇,預設是 hash
})

2.4 將路由注入應用

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

2.5 定義路由路口(a連結位置)

<router-link to="/a">go to A</router-link>
<router-link to="/b">go to B</router-link>

2.6 定義路由出口(內容展示位置)

<router-view></router-view>

2.7 定義預設路由和404路由

const routes = [
  //預設路由,匹配 /
  {path: '/', component: A},
  
  {path: '/a', component: A},
  {path: '/b', component: B},
  
  //使用萬用字元放在路由表最後匹配404路由
  {path: '*', component: NotFound}
]

3. VueRouter 例項的使用

將 VueRouter 例項 router 注入到 Vue 應用中後,VueRouter 內部做了一些操作,將 router 例項相關的資訊定義在了 Vue 的原型上,以便於所有 Vue 元件內部都可以訪問到 router 例項。

$router :建立的路由例項,包含所有路由資訊
$route:當前路由資訊物件

4. 動態路由

在路由表中將 path 屬性引數的前面加 :

const routes = [
  {path: '/', component: B},
  
  //動態路由
  {path: '/a/:id', component: A},
  
  {path: '/b', component: B},
  {path: '*', component: NotFound}
]

這樣一來, /a/1/a/2 都會顯示元件 A

//A.vue
<template>
    <div>
        我是 A 元件的內容,我收到的引數為 {{$route.params.id}}
    </div>
</template>
<script>
export default {
    mounted(){
        console.log(this.$route.params.id)
    },
    watch: {
        $route(to, from){
            console.log(this.$router)
            console.log(`路由變了,從 ${from.params.id} 變到了 ${to.params.id}`)
        }
    }
}
</script>

5. 巢狀路由

Vue Router 是在每一個路由配置物件裡添加了一個 children 屬性,用於巢狀路由。使用方法如下:

const routes = [
  {path: '/', component: A, children: [
    {path: '', component: A0},
  ]},
  {path: '/a', component: A, children: [
  
    //匹配''空白字元是指在 url 為 /a 時 A.vue 中 RouterView 顯示的內容
    {path: '', component: A0},
    
    {path: '1', component: A1},
    {path: '2', component: A2}
  ]},
  {path: '/b', component: B},
  {path: '*', component: NotFound}
]
//A.vue
<template>
    <div>
        我是 A 元件的內容
        <router-link  to="/a/1">go to A1</router-link>
        <router-link  to="/a/2">go to A2</router-link>
        <router-view></router-view>
    </div>
</template>