1. 程式人生 > >Vue Router (一)基礎篇

Vue Router (一)基礎篇

簡介

使用 Vue.js ,可以通過組合元件來組成應用程式,當你要把 vue-router 新增進來,我們需要做的是,將元件(components)對映到路由(routes),然後告訴 vue-router 在哪裡渲染它們。

安裝

npm install vue-router

 如果在一個模組化工程中使用它,必須要通過 Vue.use() 明確地安裝路由功能:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
// 1. 定義、引用(路由)元件。 
const Foo = { template: '<div>foo</div>' } import Bar from '@/views/bar.vue' // 2. 定義路由 const routes = [ { path: '/foo', name: 'foo', component: Foo }, { path: '/bar', name: 'bar', component: Bar } ] // 3. 建立 router 例項,然後傳 `routes` 配置 const router = new VueRouter({   // (縮寫)相當於 routes: routes
  routes }) // 4. 建立和掛載根例項。通過 router 配置引數注入路 const app = new Vue({ router }).$mount('#app')

動態路由分配

兩種方式傳遞$route.params$route.query

模式 匹配路徑     獲取引數(路由資訊物件)
/user/:username   /user/ligang $route.params.username
/user?:username
/user?username=ligang $route.query.username

 

 

     
  
       

 巢狀路由

 1 routes: [{
 2  path: '/user/:id', component: User, 
 3 children: [
 4  // 匹配 /user/:id 
 5 { path: '', component: UserHome },
 6  // 匹配 /user/:id/profile
 7  { path: 'profile', component: UserProfile }, 
 8 // 匹配 /user/:id/posts
 9  { path: 'posts', component: UserPosts }
10  ] 
11 }]

要注意,以 / 開頭的巢狀路徑會被當作根路徑。 這讓你充分的使用巢狀元件而無須設定巢狀的路徑。

程式設計式導航

除了使用 <router-link> 建立 a 標籤來定義導航連結,我們還可以藉助 router 的例項方法,通過編寫程式碼來實現。

 1 // 字串
 2 router.push('home')
 3 
 4 // 物件
 5 router.push({ path: 'home' })
 6 
 7 // 命名的路由
 8 router.push({ name: 'user', params: { userId: 123 }})
 9 
10 // 帶查詢引數,變成 /register?plan=private
11 router.push({ path: 'register', query: { plan: 'private' }})

注意:如果提供了 pathparams 會被忽略,上述例子中的 query 並不屬於這種情況。取而代之的是下面例子的做法,你需要提供路由的 name 或手寫完整的帶有引數的 path

1 const userId = 123
2 router.push({ name: 'user', params: { userId }}) // -> /user/123
3 router.push({ path: `/user/${userId}` }) // -> /user/123
4 // 這裡的 params 不生效
5 router.push({ path: '/user', params: { userId }}) // -> /user

同樣的規則也適用於 router-link 元件的 to 屬性

命名路由

有時候,通過一個名稱來標識一個路由顯得更方便一些,特別是在連結一個路由,或者是執行一些跳轉的時候。你可以在建立 Router 例項的時候,在 routes 配置中給某個路由設定名稱。

1 const router = new VueRouter({
2   routes: [
3     {
4       path: '/user/:userId',
5       name: 'user',
6       component: User
7     }
8   ]
9 })

要連結到一個命名路由,可以給 router-linkto 屬性傳一個物件:

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

這跟程式碼呼叫 router.push() 是一回事

router.push({ name: 'user', params: { userId: 123 }})

向路由元件傳遞 props

預設(常規)方式:通過$route.params獲取

const User = { template: '<div>User {{ $route.params.id }}</div>' }
const router = new VueRouter({
 routes: [
  {
  path:
'/user/:id',
  component: User
  }
 ]
})

使用props解耦:只需要將props設定為true

const User = {
  props: ['id'], 
  template: '<div>User {{ id }}</div>'
  }
const router = new VueRouter({
  routes: [{
      path: '/user/:id', 
     component: User,
      props: true
   }]
  })